import { NextRequest, NextResponse } from 'next/server'
import { syncVipProducts } from '@/jobs/sync-vip-products'
import { checkVipOrders } from '@/jobs/check-vip-orders'
import { checkExpiredInvoices } from '@/jobs/check-expired-invoices'

// Secured cron endpoint - can be called by Vercel Cron, or a cron service
export async function GET(req: NextRequest) {
  const authHeader = req.headers.get('authorization')
  const cronSecret = process.env.CRON_SECRET || process.env.NEXTAUTH_SECRET

  if (authHeader !== `Bearer ${cronSecret}`) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  const job = req.nextUrl.searchParams.get('job')

  try {
    switch (job) {
      case 'sync-vip':
        const syncResult = await syncVipProducts()
        return NextResponse.json({ job, result: syncResult })

      case 'check-orders':
        const orderResult = await checkVipOrders()
        return NextResponse.json({ job, result: orderResult })

      case 'check-expired':
        const expiredResult = await checkExpiredInvoices()
        return NextResponse.json({ job, result: expiredResult })

      default:
        return NextResponse.json({ error: 'Unknown job. Use: sync-vip, check-orders, check-expired' }, { status: 400 })
    }
  } catch (error: any) {
    return NextResponse.json({ error: error.message }, { status: 500 })
  }
}
