import type { APIRoute } from 'astro';

export const GET: APIRoute = async ({ request }) => {
  const setupGuide = {
    title: "CodeREADr Integration Setup Guide",
    description: "Complete guide to setting up CodeREADr as a backup scanner for Black Canyon Tickets",
    
    overview: {
      purpose: "CodeREADr serves as a backup scanning system when the primary QR scanner fails",
      benefits: [
        "Redundancy: Ensures scanning works even if primary system fails",
        "Mobile apps: CodeREADr provides dedicated mobile scanning apps",
        "Offline capability: CodeREADr apps can work offline and sync later",
        "Real-time reporting: Advanced analytics and reporting features"
      ]
    },

    prerequisites: {
      codereadr_account: "Active CodeREADr account with API access",
      api_key: "CodeREADr API key (currently: 3bcb2250e2c9cf4adf4e807f912f907e)",
      database_migration: "Run the CodeREADr database migration",
      event_setup: "Event must be created in BCT system first"
    },

    setup_steps: [
      {
        step: 1,
        title: "Apply Database Migration",
        description: "Run the CodeREADr integration migration",
        command: "supabase migration up 20250109_codereadr_integration.sql",
        notes: "This creates the necessary tables for CodeREADr integration"
      },
      {
        step: 2,
        title: "Setup CodeREADr for Event",
        description: "Initialize CodeREADr configuration for an event",
        endpoint: "POST /api/codereadr/setup",
        request_body: {
          eventId: "uuid-of-event",
          organizationId: "uuid-of-organization"
        },
        response: {
          success: true,
          message: "CodeREADr integration setup successfully",
          config: {
            database_id: "codereadr-database-id",
            service_id: "codereadr-service-id",
            user_id: "codereadr-user-id"
          }
        }
      },
      {
        step: 3,
        title: "Test Backup Scanning",
        description: "Test the backup scanning functionality",
        endpoint: "POST /api/codereadr/scan",
        request_body: {
          ticketUuid: "ticket-uuid-to-scan",
          eventId: "uuid-of-event",
          scannedBy: "user-id-scanning"
        }
      },
      {
        step: 4,
        title: "Configure Webhooks (Optional)",
        description: "Set up real-time webhook notifications",
        webhook_url: "https://your-domain.com/api/codereadr/webhook",
        notes: "Configure in CodeREADr dashboard to receive real-time scan notifications"
      }
    ],

    usage: {
      automatic_backup: {
        description: "Backup scanning happens automatically when primary scanner fails",
        trigger: "When checkInTicket() fails, it automatically tries CodeREADr",
        indicator: "Shows yellow 'Trying backup scanner...' notification"
      },
      manual_backup: {
        description: "Users can manually trigger backup scanning",
        button: "Yellow 'Backup' button in manual entry section",
        usage: "Enter ticket UUID and click 'Backup' button"
      },
      sync_scans: {
        description: "Sync scans from CodeREADr to local database",
        endpoint: "POST /api/codereadr/sync",
        frequency: "Can be run manually or scheduled"
      }
    },

    api_endpoints: {
      setup: {
        method: "POST",
        path: "/api/codereadr/setup",
        description: "Initialize CodeREADr for an event",
        parameters: ["eventId", "organizationId"]
      },
      scan: {
        method: "POST", 
        path: "/api/codereadr/scan",
        description: "Scan a ticket using CodeREADr",
        parameters: ["ticketUuid", "eventId", "scannedBy"]
      },
      sync: {
        method: "POST",
        path: "/api/codereadr/sync", 
        description: "Sync scans from CodeREADr",
        parameters: ["eventId", "organizationId"]
      },
      status: {
        method: "GET",
        path: "/api/codereadr/sync?eventId=&organizationId=",
        description: "Get CodeREADr integration status",
        parameters: ["eventId", "organizationId"]
      },
      webhook: {
        method: "POST",
        path: "/api/codereadr/webhook",
        description: "Handle real-time scan notifications",
        parameters: ["scan_id", "service_id", "value", "timestamp"]
      }
    },

    database_schema: {
      codereadr_configs: {
        description: "Stores CodeREADr configuration per event",
        key_fields: ["event_id", "database_id", "service_id", "user_id", "status"]
      },
      codereadr_scans: {
        description: "Stores synchronized scans from CodeREADr",
        key_fields: ["codereadr_scan_id", "event_id", "ticket_uuid", "scan_timestamp"]
      },
      tickets: {
        new_column: "scan_method",
        description: "Tracks how ticket was scanned (qr, codereadr, manual, api)"
      }
    },

    troubleshooting: {
      common_issues: [
        {
          issue: "CodeREADr not configured for event",
          solution: "Run POST /api/codereadr/setup first"
        },
        {
          issue: "Backup scanning fails",
          solution: "Check API key, verify event configuration, check network connectivity"
        },
        {
          issue: "Duplicate scans",
          solution: "Sync process handles duplicates automatically"
        },
        {
          issue: "Webhook not receiving data",
          solution: "Verify webhook URL configuration in CodeREADr dashboard"
        }
      ]
    },

    security_considerations: [
      "API key is stored in application code - consider environment variables",
      "Webhook endpoint should validate requests",
      "Database access controlled by RLS policies",
      "Sync operations log all actions for audit trail"
    ],

    next_steps: [
      "Test the integration with a sample event",
      "Configure webhook notifications for real-time updates",
      "Set up automated sync scheduling",
      "Train staff on backup scanning procedures",
      "Monitor scan success rates and system performance"
    ]
  };

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