export const prerender = false;

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

export const POST: APIRoute = async ({ request }) => {
  try {
    // Get the authorization header
    const authHeader = request.headers.get('Authorization');
    if (!authHeader?.startsWith('Bearer ')) {

      return new Response(JSON.stringify({ error: 'No authorization token provided' }), {
        status: 401,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    const token = authHeader.split(' ')[1];
    
    // Verify the user
    const { data: { user }, error: authError } = await supabase.auth.getUser(token);
    if (authError || !user) {

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

    const body = await request.json();

    const { eventId } = body;
    
    if (!eventId) {

      return new Response(JSON.stringify({ error: 'Event ID is required' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Get admin client

    const supabaseAdmin = getSupabaseAdmin();

    // Check if user has access to this event using admin client

    const { data: event, error: eventError } = await supabaseAdmin
      .from('events')
      .select(`
        id,
        title,
        slug,
        organization_id
      `)
      .eq('id', eventId)
      .single();

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

    // Check if user belongs to the same organization as the event
    const { data: userData, error: userError } = await supabaseAdmin
      .from('users')
      .select('organization_id, email, role')
      .eq('id', user.id)
      .single();

    if (userError || !userData) {

      return new Response(JSON.stringify({ error: 'User not found' }), {
        status: 404,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Check if user has access (same organization OR admin role)
    const hasAccess = userData.organization_id === event.organization_id || userData.role === 'admin';
    
    if (!hasAccess) {

      return new Response(JSON.stringify({ error: 'Access denied - you do not have permission to generate PIN for this event' }), {
        status: 403,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Generate a 4-digit PIN
    const pin = Math.floor(1000 + Math.random() * 9000).toString();

    // Update the event with the new PIN using admin client
    const { error: updateError } = await supabaseAdmin
      .from('events')
      .update({
        kiosk_pin: pin,
        kiosk_pin_created_at: new Date().toISOString(),
        kiosk_pin_created_by: user.id
      })
      .eq('id', eventId);

    if (updateError) {

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

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

  } catch (error) {

    // Return a more specific error message
    const errorMessage = error instanceof Error ? error.message : 'Internal server error';
    return new Response(JSON.stringify({ 
      error: errorMessage,
      details: error instanceof Error ? error.stack : 'Unknown error'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};