import { NextResponse } from 'next/server';
import { z } from 'zod';
import { sql } from 'drizzle-orm';
import { db } from '@server/db/drizzle';
import { initDatabase } from '@server/db/init';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withValidation, ParsedRequest } from '@server/middleware/withValidation';
import { ValidationError } from '@server/errors';
import { issueOtp } from '@server/services/email/otp.service';

const schema = z.object({ email: z.string().email() });

export const POST = withErrorHandler(
  withValidation(schema, async (req: ParsedRequest<z.infer<typeof schema>>) => {
    await initDatabase();
    const email = req.parsedBody.email.toLowerCase().trim();

    const { rows } = await db.execute(sql`SELECT payload FROM pending_signups WHERE email = ${email} AND expires_at > NOW() LIMIT 1`);
    if (!rows[0]) {
      await db.execute(sql`DELETE FROM pending_signups WHERE email = ${email} AND expires_at <= NOW()`);
      throw new ValidationError('Your signup session has expired — please register again');
    }

    const payload = (rows[0] as { payload: { name?: string } }).payload;
    const result = await issueOtp(email, 'signup_verify', { name: payload?.name });

    return NextResponse.json({ ok: true, throttled: result.alreadySentRecently });
  })
);
