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

export interface DeactivatePartnerInput {
  id: string;
  from?: string[];
}

/**
 * Function: deactivatePartner
 *
 * Transitions a business partner from ACTIVE to INACTIVE status,
 * preserving it for audit trails while preventing new transactions.
 */
export async function run(db: Transaction, input: DeactivatePartnerInput) {
  const { id, from } = input;

  // 1. Check partner exists
  const partner = await db
    .selectFrom("BusinessPartner")
    .selectAll()
    .where("id", "=", id)
    .forUpdate()
    .executeTakeFirst();

  if (!partner) {
    return err(new PartnerNotFoundError(id));
  }

  // 2. Check status is valid for deactivation
  const validFromStatuses = from ?? ["ACTIVE"];
  if (!validFromStatuses.includes(partner.status)) {
    return err(new InvalidStateTransitionError(`${partner.status} to INACTIVE`));
  }

  // 3. Update status to INACTIVE
  const deactivatedPartner = await db
    .updateTable("BusinessPartner")
    .set({ status: "INACTIVE", updatedAt: new Date() })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ partner: deactivatedPartner });
}
