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 ReactivatePartnerInput {
  id: string;
  from?: string[];
}

/**
 * Function: reactivatePartner
 *
 * Transitions a business partner from INACTIVE back to ACTIVE status,
 * restoring a previously deactivated partner for transactions.
 */
export async function run(db: Transaction, input: ReactivatePartnerInput) {
  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 reactivation
  const validFromStatuses = from ?? ["INACTIVE"];
  if (!validFromStatuses.includes(partner.status)) {
    return err(new InvalidStateTransitionError(`${partner.status} to ACTIVE`));
  }

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

  return ok({ partner: reactivatedPartner });
}
