import type { APIRoute } from 'astro';
import { query } from '../../../lib/db';
import { signUserToken, setUserCookie } from '../../../lib/user-auth';

export const GET: APIRoute = async ({ request, redirect }) => {
  try {
    const url = new URL(request.url);
    const token = url.searchParams.get('token');
    const isLogin = url.searchParams.get('login') === '1';

    if (!token) return redirect('/');

    let user;
    if (isLogin) {
      const result = await query(
        'SELECT id, email FROM users WHERE magic_link_token = $1 AND magic_link_expires_at > NOW()',
        [token]
      );
      if (!result.rows.length) {
        return redirect('/?error=expired');
      }
      user = result.rows[0];
      await query('UPDATE users SET magic_link_token = NULL, magic_link_expires_at = NULL, email_verified = true WHERE id = $1', [user.id]);
    } else {
      const result = await query(
        'SELECT id, email FROM users WHERE verification_token = $1',
        [token]
      );
      if (!result.rows.length) {
        return redirect('/?error=invalid');
      }
      user = result.rows[0];
      await query('UPDATE users SET email_verified = true, verification_token = NULL WHERE id = $1', [user.id]);
    }

    const jwt = signUserToken({ id: user.id, email: user.email });
    
    return new Response(null, {
      status: 302,
      headers: {
        'Location': '/watchlist',
        'Set-Cookie': setUserCookie(jwt),
      },
    });
  } catch (err) {
    console.error('Verify error:', err);
    return new Response('Er ging iets mis', { status: 500 });
  }
};
