import { Hono } from 'hono';
import { decryptSecret } from '../crypto/aes';
import { computeTotpCode, normalizeBase32Secret } from '../crypto/totp';
import { isValidShareToken } from '../lib/shareToken';

type ShareRow = {
  id: string;
  label: string;
  issuer: string | null;
  encrypted_secret: string;
  algorithm: string;
  digits: number;
  period: number;
};

/** 公开接口：仅凭 share_token 返回单条验证码，无需登录 */
export function registerShareRoutes(api: Hono<{ Bindings: Env }>): void {
  api.get('/:token', async (c) => {
    const token = c.req.param('token');
    if (!isValidShareToken(token)) {
      return c.json({ error: '无效的分享链接' }, 400);
    }

    const row = await c.env.DB.prepare(
      `SELECT id, label, issuer, encrypted_secret, algorithm, digits, period
       FROM totp_accounts WHERE share_token = ?`,
    )
      .bind(token)
      .first<ShareRow>();

    if (!row) {
      return c.json({ error: '链接无效或已失效' }, 404);
    }

    let secret: string;
    try {
      secret = await decryptSecret(c.env.MASTER_KEY, row.encrypted_secret);
    } catch {
      return c.json({ error: '无法生成验证码' }, 500);
    }

    const now = Date.now();
    const { code, expiresInSeconds } = await computeTotpCode(
      normalizeBase32Secret(secret),
      {
        digits: row.digits,
        period: row.period,
        algorithm: row.algorithm,
        nowMs: now,
      },
    );

    return c.json({
      account: {
        label: row.label,
        issuer: row.issuer,
        algorithm: row.algorithm,
        digits: row.digits,
        period: row.period,
        code,
        expiresInSeconds,
      },
    });
  });
}
