import { getDb } from '../db/client.js'

const sql = getDb()

// Default tiers as fallback
const DEFAULT_TIERS = [
  { duration_minutes: 1, price: 5000, label: '1 Menit (Test)' },
  { duration_minutes: 15, price: 30000, label: '15 Menit' },
  { duration_minutes: 30, price: 60000, label: '30 Menit' },
  { duration_minutes: 45, price: 100000, label: '45 Menit' },
  { duration_minutes: 60, price: 150000, label: '60 Menit' },
  { duration_minutes: 1440, price: 250000, label: '24 Jam' },
]

export const getPriceTiers = async () => {
  const [row] = await sql`SELECT value FROM app_config WHERE key = 'price_tiers'`
  return row?.value?.tiers ?? DEFAULT_TIERS
}

export const isValidTier = async (durationMinutes, price) => {
  const tiers = await getPriceTiers()
  return tiers.some(
    (t) => t.duration_minutes === durationMinutes && t.price === price
  )
}

export const getFreeTrial = async () => {
  const [enabledRow] = await sql`SELECT value FROM app_config WHERE key = 'free_trial_enabled'`
  const [durationRow] = await sql`SELECT value FROM app_config WHERE key = 'free_trial_duration_minutes'`
  return {
    enabled: enabledRow?.value?.value ?? false,
    duration_minutes: durationRow?.value?.value ?? 5,
  }
}

export const isCustomerEligibleForFreeTrial = async (customerId) => {
  const freeTrial = await getFreeTrial()
  if (!freeTrial.enabled) return false

  const [tx] = await sql`
    SELECT id FROM customer_transactions
    WHERE customer_id = ${customerId}
    LIMIT 1
  `
  return !tx // Eligible only if no transactions at all
}

export const getPricingForCustomer = async (customerId) => {
  const tiers = await getPriceTiers()
  const freeTrialEligible = await isCustomerEligibleForFreeTrial(customerId)
  const freeTrial = await getFreeTrial()

  return {
    tiers,
    free_trial: freeTrialEligible
      ? { eligible: true, duration_minutes: freeTrial.duration_minutes }
      : { eligible: false },
  }
}
