import type { Transaction } from "../generated/kysely-tailordb";
import {
  CompanyNotFoundError,
  InvalidLegalNameError,
  CurrencyNotFoundError,
  CurrencyImmutableError,
} from "../lib/errors.generated";
import type { PrimitivesQueries } from "../module";
import { ok, err, type CommandContext } from "@tailor-platform/erp-kit/module";

export type UpdateCompanyInput = {
  companyId: string;
  legalName?: string;
  taxId?: string;
  registrationNumber?: string;
  baseCurrencyId?: string;
  street?: string;
  city?: string;
  state?: string;
  postalCode?: string;
  country?: string;
};
/**
 * Function: updateCompany
 *
 * Modifies an existing company's attributes. Legal name validation applies when
 * provided. Base currency can only be changed while the company is in DRAFT status.
 */
export async function run<CF extends Record<string, unknown>>(
  db: Transaction,
  input: UpdateCompanyInput & Omit<Partial<CF>, "status">,
  ctx: CommandContext,
  primitivesQueries?: Pick<PrimitivesQueries, "getCurrency">,
) {
  const {
    companyId,
    legalName,
    taxId,
    registrationNumber,
    baseCurrencyId,
    street,
    city,
    state,
    postalCode,
    country,
    ...customFields
  } = input;

  // 1. Find company by id with forUpdate
  const existing = await db
    .selectFrom("Company")
    .selectAll()
    .where("id", "=", companyId)
    .forUpdate()
    .executeTakeFirst();

  if (!existing) {
    return err(new CompanyNotFoundError(companyId));
  }

  // 2. If legalName provided and empty, error
  if (legalName?.trim() === "") {
    return err(new InvalidLegalNameError(legalName));
  }

  // 3. If baseCurrencyId provided, company must be DRAFT and currency must be valid
  if (baseCurrencyId !== undefined) {
    if (existing.status !== "DRAFT") {
      return err(new CurrencyImmutableError(companyId));
    }
    if (primitivesQueries) {
      const { currency } = (await primitivesQueries.getCurrency(db, { id: baseCurrencyId }, ctx))
        .value;
      if (!currency?.isActive) {
        return err(new CurrencyNotFoundError(baseCurrencyId));
      }
    }
  }

  // 4. Build update object from provided fields — strip reserved model columns from customFields
  const RESERVED_KEYS = new Set([
    "id",
    "status",
    "legalName",
    "taxId",
    "registrationNumber",
    "baseCurrencyId",
    "street",
    "city",
    "state",
    "postalCode",
    "country",
    "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 (legalName !== undefined) updateData.legalName = legalName;
  if (taxId !== undefined) updateData.taxId = taxId;
  if (registrationNumber !== undefined) updateData.registrationNumber = registrationNumber;
  if (baseCurrencyId !== undefined) updateData.baseCurrencyId = baseCurrencyId;
  if (street !== undefined) updateData.street = street;
  if (city !== undefined) updateData.city = city;
  if (state !== undefined) updateData.state = state;
  if (postalCode !== undefined) updateData.postalCode = postalCode;
  if (country !== undefined) updateData.country = country;

  const company = await db
    .updateTable("Company")
    .set(updateData)
    .where("id", "=", companyId)
    .returningAll()
    .executeTakeFirst();

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