import type { APIRoute } from 'astro';

const OPENAI_API_KEY = process.env.OPENAI_API_KEY;

// Fallback responses when OpenAI is not available
const getFallbackResponse = (message: string): string => {
  const lowerMessage = message.toLowerCase();
  
  if (lowerMessage.includes('create') && lowerMessage.includes('event')) {
    return "To create your first event:\n\n1. Complete your account setup\n2. Connect your Stripe account\n3. Click 'Create Event' in your dashboard\n4. Fill in event details and ticket types\n5. Publish your event\n\nFor detailed steps, check our Getting Started guide at /docs/getting-started/first-event";
  }
  
  if (lowerMessage.includes('stripe') || lowerMessage.includes('payment')) {
    return "To set up payments:\n\n1. Go to Settings → Payment Settings\n2. Click 'Connect Stripe Account'\n3. Complete the verification process\n4. Start accepting payments!\n\nOur platform fee is 2.5% + $1.50 per ticket. For detailed setup instructions, visit /docs/getting-started/stripe-connect";
  }
  
  if (lowerMessage.includes('scan') || lowerMessage.includes('qr')) {
    return "QR code scanning is simple:\n\n1. Go to portal.blackcanyontickets.com/scan on any mobile device\n2. Log in with your organizer account\n3. Select your event\n4. Allow camera access\n5. Start scanning tickets!\n\nNo apps required - works in any browser. Check out our scanning guide at /docs/scanning/setup";
  }
  
  if (lowerMessage.includes('fee') || lowerMessage.includes('cost')) {
    return "Our transparent pricing is 2.5% + $1.50 per ticket.\n\nThis includes:\n• Payment processing through Stripe\n• QR code generation and scanning\n• Event management tools\n• Customer support\n• Real-time analytics\n\nFees are automatically deducted before payouts.";
  }
  
  if (lowerMessage.includes('payout') || lowerMessage.includes('paid')) {
    return "Payments are processed automatically through Stripe Connect:\n\n• Automatic processing after each sale\n• Platform fees deducted automatically\n• Typical payout time: 2-7 business days\n• Direct deposit to your bank account\n• Real-time tracking in your dashboard\n\nView detailed payout info in your Stripe dashboard.";
  }
  
  return "I'm here to help with Black Canyon Tickets! You can ask me about:\n\n• Creating and managing events\n• Setting up Stripe payments\n• QR code scanning\n• Platform fees and payouts\n• Technical troubleshooting\n\nFor detailed documentation, visit /docs or email support@blackcanyontickets.com for personal assistance.";
};

const SYSTEM_PROMPT = `You are a helpful customer support assistant for Black Canyon Tickets, a premium ticketing platform for upscale venues. 

Key information about our platform:
- We serve upscale venues and premium events
- Features include QR code scanning, Stripe payment processing, event management
- No mobile apps required - everything works in web browsers
- Platform fee is 2.5% + $1.50 per ticket
- Automatic payouts through Stripe Connect
- Events are accessed at portal.blackcanyontickets.com/e/[event-slug]
- QR scanning is available at /scan
- Mobile-friendly design for all features

Common topics:
- Account setup and verification
- Creating events and ticket types
- Payment processing and payouts
- QR code ticket scanning
- Embedding events on websites
- Troubleshooting checkout issues

Be helpful, professional, and concise. If you don't know something specific, direct them to support@blackcanyontickets.com.
Keep responses under 200 words unless asked for detailed explanations.`;

export const POST: APIRoute = async ({ request }) => {
  let message = '';
  try {
    const body = await request.json();
    message = body.message;

    if (!OPENAI_API_KEY) {
      // Use fallback responses when OpenAI is not configured
      const fallbackResponse = getFallbackResponse(message);
      return new Response(JSON.stringify({ 
        message: fallbackResponse
      }), {
        status: 200,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    const response = await fetch('https://api.openai.com/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${OPENAI_API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        model: 'gpt-3.5-turbo',
        messages: [
          { role: 'system', content: SYSTEM_PROMPT },
          { role: 'user', content: message }
        ],
        max_tokens: 300,
        temperature: 0.7,
      }),
    });

    if (!response.ok) {
      throw new Error(`OpenAI API error: ${response.status}`);
    }

    const data = await response.json();
    const assistantMessage = data.choices[0].message.content;

    return new Response(JSON.stringify({ 
      message: assistantMessage 
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });

  } catch (error) {
    // Log error and fall back to basic response
    console.error('Chat API error:', error);
    
    // Try to provide a fallback response
    const fallbackResponse = getFallbackResponse(message);
    return new Response(JSON.stringify({ 
      message: fallbackResponse,
      fallback: true
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};