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

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

/**
 * Function: activatePartner
 *
 * Transitions a business partner from DRAFT to ACTIVE status.
 */
export async function run(db: Transaction, input: ActivatePartnerInput) {
  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 activation
  const validFromStatuses = from ?? ["DRAFT"];
  if (!validFromStatuses.includes(partner.status)) {
    return err(new InvalidStateTransitionError(`${partner.status} to ACTIVE`));
  }

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

  return ok({ partner: activatedPartner });
}
