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

export interface DeleteCompanyInput {
  companyId: string;
}

/**
 * Function: deleteCompany
 *
 * Permanently removes a DRAFT company from the system. Companies with existing
 * departments or sites cannot be deleted.
 */
export async function run(db: Transaction, input: DeleteCompanyInput) {
  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. Must be DRAFT
  if (existing.status !== "DRAFT") {
    return err(new InvalidStateError(companyId));
  }

  // 3. Check for departments
  const department = await db
    .selectFrom("Department")
    .selectAll()
    .where("companyId", "=", companyId)
    .executeTakeFirst();

  if (department) {
    return err(new HasDepartmentsError(companyId));
  }

  // 4. Check for sites
  const site = await db
    .selectFrom("Site")
    .selectAll()
    .where("companyId", "=", companyId)
    .executeTakeFirst();

  if (site) {
    return err(new HasSitesError(companyId));
  }

  // 5. Delete company
  await db.deleteFrom("Company").where("id", "=", companyId).execute();

  return ok({ companyId });
}
