import 'server-only'

import { createAdminClient } from '@/lib/supabase/admin'
import { isMissingColumn } from '@/lib/db-compat'
import { CURRENT_PLAN } from '@/lib/demo/credits'

/**
 * Prepaid Express Route credits — a REAL, decrementing number (Task 69).
 *
 * Nash: "if I have an active balance of prepaid express routes… it should show
 * me there that I have, you know, 15 available. When I buy one, it's gonna go
 * drop to 14, to 13, and so on."
 *
 * Until the billing backend exists, the plan is the pilot's `CURRENT_PLAN` and
 * usage is derived from what the user actually ordered: every route request
 * this user placed with `paid_with = 'credit'` in the current calendar month
 * (the strategy doc: monthly credits reset each cycle and do not roll over).
 * The billing backend can later replace this formula without touching the UI.
 *
 * Before migration 0011 the `paid_with` column does not exist → nothing has
 * been paid with credits → the full plan allowance shows.
 */
export interface RouteCreditBalance {
  planName: string
  included: number
  used: number
  remaining: number
}

export async function getRouteCreditBalance(user: { id: string }): Promise<RouteCreditBalance> {
  const admin = createAdminClient()
  const now = new Date()
  const cycleStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString()

  const { count, error } = await admin
    .from('service_requests')
    .select('id', { count: 'exact', head: true })
    .eq('type', 'route_request')
    .eq('requested_by', user.id)
    .eq('paid_with', 'credit')
    .neq('status', 'cancelled')
    .gte('created_at', cycleStart)

  const used = isMissingColumn(error, 'paid_with') || error ? 0 : (count ?? 0)
  const included = CURRENT_PLAN.routes
  return {
    planName: CURRENT_PLAN.name,
    included,
    used,
    remaining: Math.max(included - used, 0),
  }
}
