import type { APIRoute } from 'astro';
import { query } from '../../../lib/db';
import { findOrCreateUser, generateToken } from '../../../lib/user-auth';
import { sendVerificationEmail } from '../../../lib/email';

export const POST: APIRoute = async ({ request }) => {
  try {
    const { email } = await request.json();
    if (!email || !email.includes('@')) {
      return new Response(JSON.stringify({ error: 'Ongeldig emailadres' }), { status: 400 });
    }

    const user = await findOrCreateUser(email);
    
    if (user.email_verified) {
      return new Response(JSON.stringify({ error: 'Email is al geregistreerd. Gebruik inloggen.' }), { status: 400 });
    }

    const token = generateToken();
    await query('UPDATE users SET verification_token = $1 WHERE id = $2', [token, user.id]);
    
    await sendVerificationEmail(email, token);

    return new Response(JSON.stringify({ ok: true, message: 'Check je email voor de bevestigingslink!' }));
  } catch (err) {
    console.error('Register error:', err);
    return new Response(JSON.stringify({ error: 'Er ging iets mis' }), { status: 500 });
  }
};
