import { Hono } from 'hono';
import { verifySessionToken } from './middleware/session';
import { registerAuthRoutes } from './routes/auth';
import { registerAccountRoutes } from './routes/accounts';
import { registerImportExportRoutes } from './routes/importExport';
import { registerShareRoutes } from './routes/share';

const app = new Hono<{ Bindings: Env }>();

app.onError((err, c) => {
  console.error('[sprout2fa] unhandled', err);
  return c.json(
    { error: err instanceof Error ? err.message : '服务器错误' },
    500,
  );
});

// 必须先注册更具体的前缀 /api/auth，避免被 /api 子应用吞掉
const apiAuth = new Hono<{ Bindings: Env }>();
registerAuthRoutes(apiAuth);
app.route('/api/auth', apiAuth);

const apiShare = new Hono<{ Bindings: Env }>();
registerShareRoutes(apiShare);
app.route('/api/share', apiShare);

const authed = new Hono<{ Bindings: Env }>();
authed.use('*', async (c, next) => {
  const ok = await verifySessionToken(
    c.env.SESSION_SECRET,
    c.req.header('Cookie') ?? null,
  );
  if (!ok) {
    return c.json({ error: '未授权' }, 401);
  }
  await next();
});

registerAccountRoutes(authed);
registerImportExportRoutes(authed);
app.route('/api', authed);

export default {
  async fetch(
    request: Request,
    env: Env,
    ctx: ExecutionContext,
  ): Promise<Response> {
    const url = new URL(request.url);
    if (url.pathname.startsWith('/api')) {
      return app.fetch(request, env, ctx);
    }
    return env.ASSETS.fetch(request);
  },
};