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

export interface DeactivateCompanyInput {
  companyId: string;
}

/**
 * Function: deactivateCompany
 *
 * Transitions a company from ACTIVE to INACTIVE status, preventing it from
 * being used in new transactions while preserving historical data.
 */
export async function run(db: Transaction, input: DeactivateCompanyInput) {
  const { companyId } = input;

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

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

  // 2. Check status is ACTIVE
  if (existing.status !== "ACTIVE") {
    return err(new InvalidStateError(companyId));
  }

  // 3. Set status INACTIVE
  const company = await db
    .updateTable("Company")
    .set({
      status: "INACTIVE",
      updatedAt: new Date(),
    })
    .where("id", "=", companyId)
    .returningAll()
    .executeTakeFirst();

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