import { createClient } from "@/lib/supabase/server"

export interface VoucherData {
  id: string
  serial_number: string
  pin: string
  amount: number
  currency: string
  student_type: "local" | "international"
  is_used: boolean
  used_by?: string
  used_at?: string
  created_at: string
  expires_at: string
}

export async function generateVoucher(studentType: "local" | "international", quantity = 1) {
  try {
    const supabase = await createClient()

    const amount = studentType === "local" ? 250.0 : 50.0
    const currency = studentType === "local" ? "GHS" : "USD"

    const vouchers = []

    for (let i = 0; i < quantity; i++) {
      // Generate unique serial number
      const serialNumber = await generateUniqueSerial()
      const pin = generatePin()

      const { data, error } = await supabase
        .from("vouchers")
        .insert({
          serial_number: serialNumber,
          pin: pin,
          amount: amount,
          currency: currency,
          student_type: studentType,
        })
        .select()
        .single()

      if (error) {
        console.error("Error generating voucher:", error)
        throw new Error("Failed to generate voucher")
      }

      vouchers.push(data)
    }

    return vouchers
  } catch (error) {
    console.error("Supabase configuration error:", error)
    throw new Error("Database not configured. Please set up Supabase integration.")
  }
}

export async function validateVoucher(serialNumber: string, pin: string) {
  try {
    const supabase = await createClient()

    const { data, error } = await supabase
      .from("vouchers")
      .select("*")
      .eq("serial_number", serialNumber)
      .eq("pin", pin)
      .eq("is_used", false)
      .gt("expires_at", new Date().toISOString())
      .single()

    if (error || !data) {
      return { valid: false, message: "Invalid or expired voucher" }
    }

    return { valid: true, voucher: data }
  } catch (error) {
    console.error("Supabase configuration error:", error)
    return { valid: false, message: "Database not configured. Please set up Supabase integration." }
  }
}

export async function useVoucher(voucherId: string, userId: string) {
  try {
    const supabase = await createClient()

    const { data, error } = await supabase
      .from("vouchers")
      .update({
        is_used: true,
        used_by: userId,
        used_at: new Date().toISOString(),
      })
      .eq("id", voucherId)
      .eq("is_used", false)
      .select()
      .single()

    if (error) {
      console.error("Error using voucher:", error)
      throw new Error("Failed to use voucher")
    }

    return data
  } catch (error) {
    console.error("Supabase configuration error:", error)
    throw new Error("Database not configured. Please set up Supabase integration.")
  }
}

async function generateUniqueSerial(): Promise<string> {
  const supabase = await createClient()
  let attempts = 0
  const maxAttempts = 10

  while (attempts < maxAttempts) {
    const year = new Date().getFullYear()
    const randomNum = Math.floor(Math.random() * 999999) + 1
    const serial = `FU-${year}-${randomNum.toString().padStart(6, "0")}`

    // Check if serial already exists
    const { data } = await supabase.from("vouchers").select("id").eq("serial_number", serial).single()

    if (!data) {
      return serial
    }

    attempts++
  }

  throw new Error("Failed to generate unique serial number")
}

function generatePin(): string {
  return Math.floor(Math.random() * 99999999 + 1)
    .toString()
    .padStart(8, "0")
}

export async function getVoucherStats() {
  try {
    const supabase = await createClient()

    const { data: totalVouchers } = await supabase.from("vouchers").select("id", { count: "exact" })

    const { data: usedVouchers } = await supabase.from("vouchers").select("id", { count: "exact" }).eq("is_used", true)

    const { data: localVouchers } = await supabase
      .from("vouchers")
      .select("id", { count: "exact" })
      .eq("student_type", "local")

    const { data: internationalVouchers } = await supabase
      .from("vouchers")
      .select("id", { count: "exact" })
      .eq("student_type", "international")

    return {
      total: totalVouchers?.length || 0,
      used: usedVouchers?.length || 0,
      available: (totalVouchers?.length || 0) - (usedVouchers?.length || 0),
      local: localVouchers?.length || 0,
      international: internationalVouchers?.length || 0,
    }
  } catch (error) {
    console.error("Supabase configuration error:", error)
    return {
      total: 0,
      used: 0,
      available: 0,
      local: 0,
      international: 0,
    }
  }
}
