// src/lib/api/tenants.ts
import { api } from "@/src/lib/api/client"

export type TenantStatus = "active" | "suspended"

export type Tenant = {
  id: number
  name: string
  slug: string
  status: TenantStatus
  plan?: string | null

  country?: string | null
  city?: string | null
  address_line1?: string | null
  address_line2?: string | null
  postal_code?: string | null
  phone?: string | null
  email?: string | null
  website?: string | null
  timezone?: string | null
  currency?: string | null

  created_at: string
}

export type TenantCreate = Omit<Tenant, "id" | "slug" | "created_at">

export type LicensePlan = "annual" | "lifetime"

export type TenantLicense = {
  id: number
  tenant: number
  plan: LicensePlan
  starts_at: string       // "YYYY-MM-DD"
  expires_at: string | null
  is_active: boolean
  notes: string
  is_expired: boolean
  days_remaining: number | null
  created_by: number | null
  created_at: string
  updated_at: string
}

export type TenantLicensePayload = {
  plan: LicensePlan
  starts_at: string
  expires_at?: string | null
  is_active?: boolean
  notes?: string
}

// ── Tenant CRUD ─────────────────────────────────────────────────────────────

export async function listTenants(): Promise<Tenant[]> {
  return api.request<Tenant[]>("/tenants/", { method: "GET" })
}

export async function getTenant(id: number): Promise<Tenant> {
  return api.request<Tenant>(`/tenants/${id}/`, { method: "GET" })
}

export async function createTenant(payload: TenantCreate): Promise<Tenant> {
  return api.request<Tenant>("/tenants/", {
    method: "POST",
    body: JSON.stringify(payload),
  })
}

export async function updateTenant(id: number, payload: Partial<TenantCreate>): Promise<Tenant> {
  return api.request<Tenant>(`/tenants/${id}/`, {
    method: "PATCH",
    body: JSON.stringify(payload),
  })
}

export async function deleteTenant(id: number): Promise<void> {
  await api.request(`/tenants/${id}/`, { method: "DELETE" })
}

// ── Licence ──────────────────────────────────────────────────────────────────

export async function getTenantLicense(tenantId: number): Promise<TenantLicense | null> {
  return api.request<TenantLicense | null>(`/tenants/${tenantId}/license/`, { method: "GET" })
}

export async function saveTenantLicense(
  tenantId: number,
  payload: TenantLicensePayload
): Promise<TenantLicense> {
  return api.request<TenantLicense>(`/tenants/${tenantId}/license/`, {
    method: "POST",
    body: JSON.stringify(payload),
  })
}

export async function patchTenantLicense(
  tenantId: number,
  payload: Partial<TenantLicensePayload>
): Promise<TenantLicense> {
  return api.request<TenantLicense>(`/tenants/${tenantId}/license/`, {
    method: "PATCH",
    body: JSON.stringify(payload),
  })
}

export async function deleteTenantLicense(tenantId: number): Promise<void> {
  await api.request(`/tenants/${tenantId}/license/`, { method: "DELETE" })
}

// ── Export ───────────────────────────────────────────────────────────────────

export async function exportTenantData(tenantId: number, tenantSlug: string): Promise<void> {
  const BASE = process.env.NEXT_PUBLIC_API_BASE_URL?.replace(/\/+$/, "")
  if (!BASE) throw new Error("NEXT_PUBLIC_API_BASE_URL is not set")

  const { tokenStorage } = await import("@/src/lib/api/storage")
  const access = tokenStorage.getAccess()

  const res = await fetch(`${BASE}/tenants/${tenantId}/export/`, {
    headers: access ? { Authorization: `Bearer ${access}` } : {},
  })
  if (!res.ok) throw new Error(`Export failed: HTTP ${res.status}`)

  const blob = await res.blob()
  const url  = URL.createObjectURL(blob)
  const a    = document.createElement("a")
  const date = new Date().toISOString().slice(0, 10).replace(/-/g, "")
  a.href     = url
  a.download = `export_${tenantSlug}_${date}.zip`
  a.click()
  URL.revokeObjectURL(url)
}
