import type { APIRoute } from 'astro';
import { supabase } from '../../../lib/supabase';
import { hashPin, generateRandomPin, validatePin, type ScannerLockData } from '../../../lib/scanner-lock';

export const POST: APIRoute = async ({ request }) => {
  try {
    const { eventId, pin, organizerEmail } = await request.json();
    
    // Validate PIN format
    if (!pin || !validatePin(pin)) {
      return new Response(JSON.stringify({ 
        error: 'PIN must be exactly 4 digits' 
      }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    // 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' }
      });
    }
    
    // Verify event belongs to user's organization
    const { data: event, error: eventError } = await supabase
      .from('events')
      .select('id, title, start_time, organization_id, scanner_lock_enabled')
      .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 already enabled
    if (event.scanner_lock_enabled) {
      return new Response(JSON.stringify({ error: 'Scanner lock is already enabled for this event' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    // Hash the PIN
    const pinHash = await hashPin(pin);
    
    // Setup scanner lock using database function
    const { data: setupResult, error: setupError } = await supabase
      .rpc('setup_scanner_lock', {
        p_event_id: eventId,
        p_pin_hash: pinHash
      });
    
    if (setupError || !setupResult) {
      console.error('Scanner lock setup error:', setupError);
      return new Response(JSON.stringify({ error: 'Failed to setup scanner lock' }), {
        status: 500,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    // Return success response with event details for email
    return new Response(JSON.stringify({
      success: true,
      event: {
        id: event.id,
        title: event.title,
        start_time: event.start_time
      },
      pin // Return the PIN for email purposes - this will be sent securely
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
    
  } catch (error) {
    console.error('Scanner lock setup error:', error);
    return new Response(JSON.stringify({ error: 'Internal server error' }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};