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

export const POST: APIRoute = async ({ request }) => {
  try {
    const { eventId } = await request.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, 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 enabled
    if (!event.scanner_lock_enabled) {
      return new Response(JSON.stringify({ error: 'Scanner lock is not enabled for this event' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    // Disable scanner lock using database function
    const { data: disableResult, error: disableError } = await supabase
      .rpc('disable_scanner_lock', {
        p_event_id: eventId
      });
    
    if (disableError || !disableResult) {

      return new Response(JSON.stringify({ error: 'Failed to disable scanner lock' }), {
        status: 500,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    return new Response(JSON.stringify({
      success: true,
      message: 'Scanner lock disabled successfully'
    }), {
      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' }
    });
  }
};