import type { AdapterResult } from "../types";
import { commercialGet, extractItems, failResult, listResult } from "./http";

export interface CommercialInvoice {
  invoice_code: string;
  display_name?: string | null;
  status?: string | null;
  amount_minor?: number | null;
  currency?: string | null;
  issued_at?: string | null;
  href?: string | null;
  metadata?: Record<string, unknown>;
}

export interface CommercialTransaction {
  transaction_code: string;
  display_name?: string | null;
  status?: string | null;
  amount_minor?: number | null;
  currency?: string | null;
  occurred_at?: string | null;
  metadata?: Record<string, unknown>;
}

export interface CommercialLicense {
  license_code: string;
  display_name?: string | null;
  status?: string | null;
  valid_until?: string | null;
  metadata?: Record<string, unknown>;
}

export async function loadCommercialInvoices(
  tenantId: string
): Promise<AdapterResult<CommercialInvoice[]>> {
  const res = await commercialGet<unknown>(
    `/api/v1/commercial/invoices?tenant_id=${encodeURIComponent(tenantId)}`
  );
  if (!res.ok) return failResult(res.availability, res.message || "فاکتور در دسترس نیست", []);
  const items = extractItems<CommercialInvoice>(res.data, ["items", "invoices"]);
  return listResult(items, "commercial.invoices", "فاکتوری نیست");
}

export async function loadCommercialTransactions(
  tenantId: string
): Promise<AdapterResult<CommercialTransaction[]>> {
  const res = await commercialGet<unknown>(
    `/api/v1/commercial/transactions?tenant_id=${encodeURIComponent(tenantId)}`
  );
  if (!res.ok) return failResult(res.availability, res.message || "تراکنش در دسترس نیست", []);
  const items = extractItems<CommercialTransaction>(res.data, ["items", "transactions"]);
  return listResult(items, "commercial.transactions", "تراکنشی نیست");
}

export async function loadCommercialLicenses(
  tenantId: string
): Promise<AdapterResult<CommercialLicense[]>> {
  const res = await commercialGet<unknown>(
    `/api/v1/commercial/licenses?tenant_id=${encodeURIComponent(tenantId)}`
  );
  if (!res.ok) return failResult(res.availability, res.message || "لایسنس در دسترس نیست", []);
  const items = extractItems<CommercialLicense>(res.data, ["items", "licenses"]);
  return listResult(items, "commercial.licenses", "لایسنسی نیست");
}
