import { ok, err, type CommandContext } from "@tailor-platform/erp-kit/core";
import { auditPolicyLifecycle } from "../db/auditPolicy.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import { PolicyNotFoundError, InvalidStateError, UnauthorizedError } from "../lib/errors.generated";

export interface DeactivateAuditPolicyInput {
  policyId: string;
}

/**
 * Function: deactivateAuditPolicy
 *
 * Transitions an audit policy from ACTIVE to INACTIVE status, stopping new
 * audit capture for the specified entity, operation type, and scope. Previously
 * recorded audit entries are not deleted.
 */
export async function run(db: Transaction, input: DeactivateAuditPolicyInput, ctx: CommandContext) {
  const { policyId } = input;

  // 1. Find policy with forUpdate
  const existing = await db
    .selectFrom("AuditPolicy")
    .selectAll()
    .where("id", "=", policyId)
    .forUpdate()
    .executeTakeFirst();

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

  // 2. Scope authorization
  if (ctx.companyId !== undefined) {
    if (ctx.companyId !== null && existing.companyId !== ctx.companyId) {
      return err(new UnauthorizedError(ctx.actorId));
    }
    if (ctx.companyId === null && existing.companyId !== null) {
      return err(new UnauthorizedError(ctx.actorId));
    }
  }

  const nextStatus = auditPolicyLifecycle.tryTransition(existing.status, "deactivate");
  if (!nextStatus) {
    return err(new InvalidStateError(policyId));
  }

  const policy = await db
    .updateTable("AuditPolicy")
    .set({
      status: nextStatus,
    })
    .where("id", "=", policyId)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ policy });
}
