import type { APIRoute } from 'astro';
import { pb } from '../../../lib/pb';

export const POST: APIRoute = async ({ request, cookies, url }) => {
  try {
    const data = await request.json();

    const { email, password, redirect } = data;

    if (!email || !password) {
      return new Response(JSON.stringify({
        success: false,
        error: 'Email и пароль обязательны'
      }), { status: 400 });
    }

    const authData = await pb.collection('users').authWithPassword(email, password);

    console.log('Auth data token:', authData.token ? 'yes' : 'no');
    console.log('Auth record id:', authData.record?.id);
    console.log('Auth record verified:', authData.record?.verified);

    // Проверяем верификацию
    if (!authData.record.verified) {
      return new Response(JSON.stringify({
        success: false,
        error: 'Email не подтверждён'
      }), { status: 401 });
    }

    cookies.set('pb_auth', authData.token, {
      path: '/',
      httpOnly: false,
      secure: false,
      sameSite: 'lax',
      maxAge: 60 * 60 * 24 * 7,
    });

    // Определяем URL для редиректа
    let redirectUrl = '/';
    if (redirect) {
      redirectUrl = redirect;
    }

    return new Response(JSON.stringify({
      success: true,
      token: authData.token,
      user: {
        id: authData.record.id,
        name: authData.record.firstName,
        email: authData.record.email,
      },
      redirect: redirectUrl
    }), { status: 200 });

  } catch (error: any) {
    console.error('Sign in error:', error);

    return new Response(JSON.stringify({
      success: false,
      error: error.message || 'Неверный email или пароль'
    }), { status: 401 });
  }
};