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

const PB_POCKETBASE_URL = import.meta.env.PB_POCKETBASE_URL || 'http://127.0.0.1:8090';
const ADMIN_EMAIL = import.meta.env.PB_ADMIN_EMAIL || 'redibedi2019@gmail.com';
const ADMIN_PASSWORD = import.meta.env.PB_ADMIN_PASSWORD || 'Stalin4444';

export const POST: APIRoute = async ({ request }) => {
  try {
    const data = await request.json();
    const { token, userId } = data;
    
    if (!token || !userId) {
      return new Response(JSON.stringify({
        success: false,
        error: 'Отсутствуют параметры'
      }), { status: 400 });
    }
    
    const decoded = Buffer.from(token, 'base64').toString('utf8');
    const parts = decoded.split(':');
    
    if (parts.length < 3) {
      return new Response(JSON.stringify({
        success: false,
        error: 'Неверный формат токена'
      }), { status: 400 });
    }
    
    const [tokenUserId, email, timestamp] = parts;
    
    if (tokenUserId !== userId) {
      return new Response(JSON.stringify({
        success: false,
        error: 'Неверный токен'
      }), { status: 400 });
    }
    
    const tokenTime = parseInt(timestamp);
    const now = Date.now();
    const maxAge = 24 * 60 * 60 * 1000;
    
    if (now - tokenTime > maxAge) {
      return new Response(JSON.stringify({
        success: false,
        error: 'Срок действия ссылки истёк'
      }), { status: 400 });
    }

    console.log('Attempting admin auth...');
    await pb.collection('_superusers').authWithPassword(ADMIN_EMAIL, ADMIN_PASSWORD);
    console.log('Admin auth success, updating user...');
    
    await pb.collection('users').update(userId, {
      verified: true,
    });
    console.log('User verified:', userId);
    
    return new Response(JSON.stringify({
      success: true,
      message: 'Email подтверждён'
    }), { status: 200 });
    
  } catch (error: any) {
    console.error('Confirm error:', error);
    
    return new Response(JSON.stringify({
      success: false,
      error: 'Ошибка при подтверждении'
    }), { status: 400 });
  }
};