import { supabase } from "@/integrations/supabase/client";
import { accounting } from "@/lib/accountingClient";

/**
 * The Chart of Accounts shape every consumer in the app expects, regardless of
 * whether the underlying source is the public `chart_of_accounts` table or the
 * Accounting platform's `accounting.accounts` table.
 */
export type NormalizedAccount = {
  id: string;
  account_number: string;
  account_name: string;
  account_type: string;
  parent_account_id: string | null;
  is_active: boolean;
  association_id: string | null;
  association_ids: string[] | null;
  accounting_system: string;
  description: string | null;
};

function fromPublic(row: any): NormalizedAccount {
  return {
    id: String(row.id),
    account_number: row.account_number ?? "",
    account_name: row.account_name ?? "Unnamed Account",
    account_type: row.account_type ?? "Uncategorized",
    parent_account_id: row.parent_account_id ?? null,
    is_active: row.is_active ?? true,
    association_id: row.association_id ?? null,
    association_ids: Array.isArray(row.association_ids) ? row.association_ids : null,
    accounting_system: row.accounting_system ?? "buildium",
    description: row.description ?? null,
  };
}

function fromPlatform(row: any, associationId: string): NormalizedAccount {
  return {
    id: String(row.id),
    account_number: row.code ?? "",
    account_name: row.name ?? "Unnamed Account",
    account_type: row.type ?? "Uncategorized",
    parent_account_id: row.parent_account_id ?? null,
    is_active: true, // accounting.accounts has no active flag; all are active
    association_id: associationId,
    association_ids: [associationId],
    accounting_system: "platform",
    description: row.subtype ?? row.description ?? null,
  };
}

/**
 * Loads the Chart of Accounts for an association's accounting system.
 * - `platform`  → the Accounting module's `accounting.accounts` (single source of
 *   truth once an association is on the platform). Returns [] if the association
 *   has no `accounting.companies` row yet.
 * - `zoho` / `buildium` → the public `chart_of_accounts`, scoped by system.
 *
 * Returned rows are normalized to {@link NormalizedAccount} so callers never
 * branch on the source.
 */
export async function fetchChartOfAccounts(
  associationId: string | null | undefined,
  system: string,
): Promise<NormalizedAccount[]> {
  if (system === "platform" && associationId) {
    const { data: company, error: companyError } = await accounting
      .from("companies")
      .select("id")
      .eq("association_id", associationId)
      .maybeSingle();
    if (companyError) throw companyError;
    if (!company?.id) return [];

    const { data, error } = await accounting
      .from("accounts")
      .select("id, code, name, type, subtype, parent_account_id, description")
      .eq("company_id", company.id)
      .order("code", { ascending: true });
    if (error) throw error;
    return (data ?? []).map((row) => fromPlatform(row, associationId));
  }

  const { data, error } = await supabase
    .from("chart_of_accounts")
    .select("*")
    .eq("accounting_system", system)
    .order("account_number", { ascending: true });
  if (error) throw error;
  return (data ?? []).map(fromPublic);
}
