import type { APIRoute } from 'astro';
import { supabase } from '../../../lib/supabase';
import { verifyPin, getDeviceInfo, type UnlockAttemptData } from '../../../lib/scanner-lock';

export const POST: APIRoute = async ({ request }) => {
  try {
    const { eventId, pin } = await request.json();
    
    // Get IP address and user agent for logging
    const ipAddress = request.headers.get('x-forwarded-for') || 
                     request.headers.get('cf-connecting-ip') || 
                     'unknown';
    const userAgent = request.headers.get('user-agent') || 'unknown';
    const deviceInfo = getDeviceInfo(userAgent);
    
    // Verify user authentication
    const authHeader = request.headers.get('Authorization');
    if (!authHeader) {
      return new Response(JSON.stringify({ error: 'Unauthorized' }), {
        status: 401,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    const { data: { user }, error: authError } = await supabase.auth.getUser(authHeader.replace('Bearer ', ''));
    if (authError || !user) {
      return new Response(JSON.stringify({ error: 'Unauthorized' }), {
        status: 401,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    // Get user's organization
    const { data: userData, error: userError } = await supabase
      .from('users')
      .select('organization_id')
      .eq('id', user.id)
      .single();
    
    if (userError || !userData?.organization_id) {
      return new Response(JSON.stringify({ error: 'User not found or not in organization' }), {
        status: 403,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    // Get event with scanner lock info
    const { data: event, error: eventError } = await supabase
      .from('events')
      .select('id, title, organization_id, scanner_lock_enabled, scanner_pin_hash')
      .eq('id', eventId)
      .eq('organization_id', userData.organization_id)
      .single();
    
    if (eventError || !event) {
      return new Response(JSON.stringify({ error: 'Event not found' }), {
        status: 404,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    // Check if scanner lock is enabled
    if (!event.scanner_lock_enabled || !event.scanner_pin_hash) {
      return new Response(JSON.stringify({ error: 'Scanner lock is not enabled for this event' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    // Verify PIN
    const isValidPin = await verifyPin(pin, event.scanner_pin_hash);
    
    // Log the unlock attempt
    const attemptResult = isValidPin ? 'SUCCESS' : 'INVALID_PIN';
    
    await supabase
      .from('scanner_unlock_attempts')
      .insert({
        event_id: eventId,
        attempted_by: user.id,
        attempt_result: attemptResult,
        ip_address: ipAddress,
        user_agent: userAgent,
        device_info: deviceInfo
      });
    
    if (isValidPin) {
      return new Response(JSON.stringify({
        success: true,
        message: 'PIN verified successfully'
      }), {
        status: 200,
        headers: { 'Content-Type': 'application/json' }
      });
    } else {
      return new Response(JSON.stringify({
        success: false,
        error: 'Invalid PIN'
      }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
  } catch (error) {

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