export const prerender = false;

import type { APIRoute } from 'astro';
import { getSupabaseAdmin } from '../../../lib/supabase-admin';

export const POST: APIRoute = async ({ request }) => {
  try {
    const { eventSlug, pin } = await request.json();
    
    if (!eventSlug || !pin) {
      return new Response(JSON.stringify({ error: 'Event slug and PIN are required' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Validate PIN format
    if (!/^\d{4}$/.test(pin)) {
      return new Response(JSON.stringify({ error: 'PIN must be exactly 4 digits' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Get admin client
    const supabaseAdmin = getSupabaseAdmin();
    
    // Find event by slug and verify PIN using admin client
    const { data: event, error: eventError } = await supabaseAdmin
      .from('events')
      .select('id, title, slug, kiosk_pin, kiosk_pin_created_at')
      .eq('slug', eventSlug)
      .single();

    if (eventError || !event) {
      return new Response(JSON.stringify({ error: 'Event not found' }), {
        status: 404,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Check if PIN exists
    if (!event.kiosk_pin) {
      return new Response(JSON.stringify({ error: 'No PIN set for this event' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Check if PIN is expired (24 hours)
    if (event.kiosk_pin_created_at) {
      const pinCreatedAt = new Date(event.kiosk_pin_created_at);
      const expirationTime = new Date(pinCreatedAt.getTime() + 24 * 60 * 60 * 1000); // 24 hours
      
      if (new Date() > expirationTime) {
        return new Response(JSON.stringify({ error: 'PIN has expired. Please generate a new one.' }), {
          status: 400,
          headers: { 'Content-Type': 'application/json' }
        });
      }
    }

    // Verify PIN
    const isValid = event.kiosk_pin === pin;

    // Log the access attempt
    const clientIP = request.headers.get('cf-connecting-ip') || 
                    request.headers.get('x-forwarded-for') || 
                    request.headers.get('x-real-ip') || 
                    'unknown';
    
    const userAgent = request.headers.get('user-agent') || 'unknown';

    await supabaseAdmin
      .from('kiosk_access_logs')
      .insert({
        event_id: event.id,
        ip_address: clientIP,
        user_agent: userAgent,
        success: isValid
      });

    if (!isValid) {
      return new Response(JSON.stringify({ error: 'Invalid PIN' }), {
        status: 401,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    return new Response(JSON.stringify({ 
      success: true,
      event: {
        id: event.id,
        title: event.title,
        slug: event.slug
      }
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });

  } catch (error) {

    return new Response(JSON.stringify({ error: 'Internal server error' }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};