import type { FastifyInstance } from 'fastify';
import { signupService } from '../services/signupService.js';
import { verifyTurnstileForNewSession } from '../services/captchaService.js';
export async function signupRoutes(fastify: FastifyInstance) {
  fastify.post('/chat', async (req, reply) => {
    const body = req.body as {
      sessionId?: string | null;
      message?: string;
      captchaToken?: string;
    };
    const sessionId = body.sessionId?.trim() ? body.sessionId.trim() : null;
    const message = typeof body.message === 'string' ? body.message : '';
    const ip = req.ip;

    if (!(await verifyTurnstileForNewSession(sessionId, body.captchaToken, ip))) {
      return reply.status(400).send({ error: 'Captcha verification failed' });
    }

    const result = await signupService.processChat({
      sessionId,
      message,
      remoteIp: ip,
    });
    return reply.send(result);
  });

  fastify.get('/verify', async (req, reply) => {
    const token = (req.query as { token?: string }).token ?? '';
    const v = await signupService.verifyToken(token);
    if (!v.ok) {
      return reply.status(400).send({ error: v.error ?? 'invalid' });
    }
    return reply.send({ ok: true, email: v.email, hint: v.hint });
  });

  fastify.post('/complete', async (req, reply) => {
    const { token, password } = req.body as { token?: string; password?: string };
    if (!token?.trim() || !password) {
      return reply.status(400).send({ error: 'token and password are required' });
    }
    const result = await signupService.completeSignup(token.trim(), password);
    if ('error' in result) {
      return reply.status(result.status).send({ error: result.error });
    }
    return reply.send({ token: result.token, user: result.user });
  });
}
