import { ok, err } from "@tailor-platform/erp-kit/core";
import { approvalPolicyLifecycle } from "../db/approvalPolicy.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import { InvalidStatusTransitionError, PolicyNotFoundError } from "../lib/errors.generated";

export interface DeactivateApprovalPolicyInput {
  id: string;
}

/**
 * Function: deactivateApprovalPolicy
 *
 * Transitions an ACTIVE ApprovalPolicy to INACTIVE and stamps deactivatedAt.
 * INACTIVE is terminal; the row is retained so that historical
 * ApprovalRequest.sourcePolicyId references remain resolvable.
 */
export async function run(db: Transaction, input: DeactivateApprovalPolicyInput) {
  const { id } = input;

  const existing = await db
    .selectFrom("ApprovalPolicy")
    .selectAll()
    .where("id", "=", id)
    .forUpdate()
    .executeTakeFirst();

  if (!existing) {
    return err(new PolicyNotFoundError(id));
  }

  const nextStatus = approvalPolicyLifecycle.tryTransition(existing.status, "deactivate");
  if (!nextStatus) {
    return err(new InvalidStatusTransitionError(id));
  }

  const now = new Date();
  const approvalPolicy = await db
    .updateTable("ApprovalPolicy")
    .set({
      status: nextStatus,
      deactivatedAt: now,
    })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ approvalPolicy });
}
