import type { APIRoute } from 'astro';
import { query } from '../../../lib/db';
import { generateToken } from '../../../lib/user-auth';
import { sendMagicLinkEmail } 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 result = await query('SELECT id, email, email_verified FROM users WHERE email = $1', [email.toLowerCase().trim()]);
    if (!result.rows.length) {
      // Don't reveal if account exists or not
      return new Response(JSON.stringify({ ok: true, message: 'Als dit emailadres bij ons bekend is, ontvang je een inloglink.' }));
    }

    const user = result.rows[0];
    const token = generateToken();
    const expiresAt = new Date(Date.now() + 3600_000); // 1 hour

    await query('UPDATE users SET magic_link_token = $1, magic_link_expires_at = $2 WHERE id = $3', [token, expiresAt, user.id]);
    await sendMagicLinkEmail(email, token);

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