import 'dotenv/config';
import { setDelegatedToken } from './userAuth.ts';

const port = Number(process.env.PORT || 3800);

function jsonResponse(data: unknown, status = 200) {
  return new Response(JSON.stringify(data), {
    status,
    headers: { 'Content-Type': 'application/json' },
  });
}

const server = Bun.serve({
  port,
  fetch: async (req: any) => {
    const url = new URL((req as any).url);

    if ((req as any).method === 'GET' && url.pathname === '/api/health') {
      return jsonResponse({ status: 'ok', service: 'token-server', timestamp: new Date().toISOString() });
    }

    if ((req as any).method === 'POST' && url.pathname === '/api/token') {
      try {
        const body = await (req as any).json();
        const token: string | undefined = body?.token;
        const expiresAt: number | undefined = body?.expiresAt;
        if (!token || typeof token !== 'string') {
          return jsonResponse({ success: false, message: 'Missing token' }, 400);
        }
        setDelegatedToken(token, typeof expiresAt === 'number' ? expiresAt : undefined);
        console.log('✓ Delegated token updated', expiresAt ? `(expiresAt=${expiresAt})` : '');
        return jsonResponse({ success: true });
      } catch (e: any) {
        return jsonResponse({ success: false, message: e?.message || 'Invalid JSON' }, 400);
      }
    }

    return jsonResponse({ success: false, message: 'Not Found' }, 404);
  },
});

console.log(`✓ Token server listening on http://localhost:${port}`);
