import { redirect, type RequestHandler } from '@sveltejs/kit';

import { consumeMagicLink, createSession } from '$lib/server/auth';

export const GET: RequestHandler = async ({ url, cookies }) => {
  const token = url.searchParams.get('token');
  if (!token) throw redirect(303, '/?error=missing-token');

  const account = consumeMagicLink(token);
  if (!account) throw redirect(303, '/?error=invalid-token');

  createSession(cookies, account.id);
  throw redirect(303, '/dashboard');
};
