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 ReactivateCompanyInput {
  companyId: string;
}

/**
 * Function: reactivateCompany
 *
 * Transitions a company from INACTIVE back to ACTIVE status, re-enabling it
 * for use in new transactions.
 */
export async function run(db: Transaction, input: ReactivateCompanyInput) {
  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 INACTIVE
  if (existing.status !== "INACTIVE") {
    return err(new InvalidStateError(companyId));
  }

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

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