import type { Transaction } from "../generated/kysely-tailordb";
import {
  ChartOfAccountsNotFoundError,
  ChartOfAccountsArchivedError,
  NameRequiredError,
} from "../lib/errors.generated";
import { ok, err, type CommandContext } from "@tailor-platform/erp-kit/module";

export type UpdateChartOfAccountsInput = {
  id: string;
  name?: string;
  description?: string | null;
};

/**
 * Function: updateChartOfAccounts
 *
 * Modifies the mutable fields (name, description) of an existing Chart of Accounts.
 * Updates are permitted while the CoA is in DRAFT or ACTIVE status.
 */
export async function run<CF extends Record<string, unknown>>(
  db: Transaction,
  input: UpdateChartOfAccountsInput & Omit<Partial<CF>, "status">,
  _ctx: CommandContext,
) {
  const { id, name, description, ...customFields } = input;

  // 1. Find CoA with forUpdate
  const existing = await db
    .selectFrom("ChartOfAccounts")
    .selectAll()
    .where("id", "=", id)
    .forUpdate()
    .executeTakeFirst();

  if (!existing) {
    return err(new ChartOfAccountsNotFoundError(id));
  }

  // 2. Must not be ARCHIVED
  if (existing.status === "ARCHIVED") {
    return err(new ChartOfAccountsArchivedError(id));
  }

  // 3. Validate name if provided
  if (name?.trim() === "") {
    return err(new NameRequiredError(id));
  }

  // 4. Build update object
  const RESERVED_KEYS = new Set([
    "id",
    "status",
    "name",
    "description",
    "companyId",
    "createdAt",
    "updatedAt",
  ]);
  const safeCustomFields: Record<string, unknown> = {};
  for (const [key, value] of Object.entries(customFields)) {
    if (!RESERVED_KEYS.has(key)) {
      safeCustomFields[key] = value;
    }
  }

  const updateData: Record<string, unknown> = {
    ...safeCustomFields,
    updatedAt: new Date(),
  };

  if (name !== undefined) updateData.name = name;
  if (description !== undefined) updateData.description = description;

  const chartOfAccounts = await db
    .updateTable("ChartOfAccounts")
    .set(updateData)
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirst();

  return ok({ chartOfAccounts: chartOfAccounts! });
}
