/**
 * Cleanup Expired Special Hours
 *
 * This edge function:
 * 1. Finds all stores that have special hours expiring today
 * 2. Deletes the expired special hours from the database
 * 3. Updates VAPI system prompts for affected stores (to remove expired hours)
 *
 * Called by pg_cron daily at midnight
 */

import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
import { updateVapiSystemPrompt } from '../_shared/vapi-setup.ts'

serve(async (req) => {
  // Verify internal call (from pg_cron or service role)
  const authHeader = req.headers.get('authorization')
  const internalSecret = Deno.env.get('INTERNAL_SYNC_SECRET')
  const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')

  // Allow either internal secret or service role key
  const isAuthorized =
    authHeader === `Bearer ${internalSecret}` ||
    authHeader === `Bearer ${supabaseServiceKey}`

  if (!isAuthorized) {
    console.error('[Cleanup] Unauthorized request')
    return new Response(
      JSON.stringify({ error: 'Unauthorized' }),
      { status: 401, headers: { 'Content-Type': 'application/json' } }
    )
  }

  const supabaseUrl = Deno.env.get('SUPABASE_URL')!
  const supabase = createClient(supabaseUrl, supabaseServiceKey!)

  console.log('[Cleanup] Starting expired special hours cleanup')

  try {
    const today = new Date().toISOString().split('T')[0]

    // Step 1: Find all stores that have special hours expiring today or earlier
    // We need to update VAPI for these stores BEFORE deleting the records
    const { data: expiringHours, error: fetchError } = await supabase
      .from('store_special_hours')
      .select('store_id')
      .lt('date', today)

    if (fetchError) {
      console.error('[Cleanup] Error fetching expiring special hours:', fetchError)
      return new Response(
        JSON.stringify({ error: 'Failed to fetch expiring special hours' }),
        { status: 500, headers: { 'Content-Type': 'application/json' } }
      )
    }

    // Get unique store IDs
    const affectedStoreIds = [...new Set((expiringHours || []).map(h => h.store_id))]
    console.log(`[Cleanup] Found ${affectedStoreIds.length} stores with expiring special hours`)

    // Step 2: Delete expired special hours
    const { error: deleteError, count: deletedCount } = await supabase
      .from('store_special_hours')
      .delete({ count: 'exact' })
      .lt('date', today)

    if (deleteError) {
      console.error('[Cleanup] Error deleting expired special hours:', deleteError)
      return new Response(
        JSON.stringify({ error: 'Failed to delete expired special hours' }),
        { status: 500, headers: { 'Content-Type': 'application/json' } }
      )
    }

    console.log(`[Cleanup] Deleted ${deletedCount} expired special hours records`)

    // Step 3: Update VAPI system prompts for affected stores
    const vapiResults: Array<{ storeId: string; success: boolean; error?: string }> = []

    for (const storeId of affectedStoreIds) {
      try {
        console.log(`[Cleanup] Updating VAPI system prompt for store: ${storeId}`)
        const result = await updateVapiSystemPrompt(supabase, storeId)

        vapiResults.push({
          storeId,
          success: result.success,
          error: result.error
        })

        if (result.success) {
          console.log(`[Cleanup] Successfully updated VAPI for store: ${storeId}`)
        } else {
          console.error(`[Cleanup] Failed to update VAPI for store ${storeId}: ${result.error}`)
        }
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : 'Unknown error'
        console.error(`[Cleanup] Error updating VAPI for store ${storeId}:`, error)
        vapiResults.push({
          storeId,
          success: false,
          error: errorMessage
        })
      }
    }

    const successCount = vapiResults.filter(r => r.success).length
    const failCount = vapiResults.filter(r => !r.success).length

    console.log(`[Cleanup] VAPI updates: ${successCount} succeeded, ${failCount} failed`)

    return new Response(
      JSON.stringify({
        success: true,
        message: 'Cleanup completed',
        deletedRecords: deletedCount,
        affectedStores: affectedStoreIds.length,
        vapiUpdates: {
          succeeded: successCount,
          failed: failCount,
          details: vapiResults
        }
      }),
      { status: 200, headers: { 'Content-Type': 'application/json' } }
    )
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : 'Unknown error'
    console.error('[Cleanup] Unexpected error:', error)
    return new Response(
      JSON.stringify({ error: errorMessage }),
      { status: 500, headers: { 'Content-Type': 'application/json' } }
    )
  }
})
