import type { APIRoute } from 'astro';
import { supabase } from '../../../lib/supabase';
import { CodereadrApi } from '../../../lib/codereadr-api';

export const POST: APIRoute = async ({ request }) => {
  try {
    const { eventId, organizationId } = await request.json();

    if (!eventId || !organizationId) {
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Missing required parameters' 
      }), { status: 400 });
    }

    // Get event details
    const { data: event, error: eventError } = await supabase
      .from('events')
      .select('*')
      .eq('id', eventId)
      .eq('organization_id', organizationId)
      .single();

    if (eventError || !event) {
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Event not found' 
      }), { status: 404 });
    }

    // Initialize CodeREADr API
    const codereadrApi = new CodereadrApi();

    // Create or get database for this event
    const dbName = `BCT-${event.title.replace(/[^a-zA-Z0-9]/g, '-')}-${eventId}`;
    let database;
    
    try {
      // Try to create database
      database = await codereadrApi.createDatabase(
        dbName,
        `Database for ${event.title} event`
      );
    } catch (error) {
      // If database exists, get it
      const databases = await codereadrApi.getDatabases();
      database = databases.find(db => db.name === dbName);
      
      if (!database) {
        throw new Error('Failed to create or find database');
      }
    }

    // Get all tickets for this event and add them to the database
    const { data: tickets, error: ticketsError } = await supabase
      .from('tickets')
      .select(`
        *,
        ticket_types (
          name,
          price
        )
      `)
      .eq('event_id', eventId);

    if (ticketsError) {
      return new Response(JSON.stringify({ 
        success: false, 
        error: 'Failed to fetch tickets' 
      }), { status: 500 });
    }

    // Add tickets to CodeREADr database
    const ticketPromises = tickets.map(ticket => {
      const response = JSON.stringify({
        valid: true,
        ticket_id: ticket.id,
        purchaser_name: ticket.purchaser_name,
        purchaser_email: ticket.purchaser_email,
        ticket_type: ticket.ticket_types?.name || 'General',
        price: ticket.ticket_types?.price || 0,
        event_title: event.title,
        message: `Valid ticket for ${event.title}`,
        action: 'checkin'
      });

      return codereadrApi.addDatabaseRecord(
        database.id,
        ticket.uuid,
        response
      );
    });

    await Promise.all(ticketPromises);

    // Create or get user for this organization
    const userName = `bct-org-${organizationId}`;
    const userEmail = `org-${organizationId}@blackcanyontickets.com`;
    let user;

    try {
      // Try to create user
      user = await codereadrApi.createUser(
        userName,
        userEmail,
        'BCT-Scanner-2024!' // Default password
      );
    } catch (error) {
      // If user exists, get it
      const users = await codereadrApi.getUsers();
      user = users.find(u => u.username === userName);
      
      if (!user) {
        throw new Error('Failed to create or find user');
      }
    }

    // Create service for this event
    const serviceName = `BCT-Scanner-${event.title}-${eventId}`;
    const service = await codereadrApi.createService(
      serviceName,
      database.id,
      user.id
    );

    // Store CodeREADr configuration in our database
    const { error: configError } = await supabase
      .from('codereadr_configs')
      .upsert({
        event_id: eventId,
        organization_id: organizationId,
        database_id: database.id,
        service_id: service.id,
        user_id: user.id,
        database_name: dbName,
        service_name: serviceName,
        user_name: userName,
        status: 'active',
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      });

    if (configError) {

      // Continue anyway, as the external setup was successful
    }

    return new Response(JSON.stringify({
      success: true,
      message: 'CodeREADr integration setup successfully',
      config: {
        database_id: database.id,
        service_id: service.id,
        user_id: user.id,
        database_name: dbName,
        service_name: serviceName,
        user_name: userName
      }
    }), { status: 200 });

  } catch (error) {

    return new Response(JSON.stringify({ 
      success: false, 
      error: error.message || 'Failed to setup CodeREADr integration' 
    }), { status: 500 });
  }
};