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

export interface DeleteAuditPolicyInput {
  policyId: string;
}

/**
 * Function: deleteAuditPolicy
 *
 * Permanently removes a DRAFT audit policy and its associated field rules.
 * Only policies in DRAFT status can be deleted.
 */
export async function run(db: Transaction, input: DeleteAuditPolicyInput, ctx: CommandContext) {
  const { policyId } = input;

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

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

  // Scope authorization checks
  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));
    }
  }

  // 2. Not DRAFT → InvalidStateError
  if (existing.status !== "DRAFT") {
    return err(new InvalidStateError(policyId));
  }

  // 3. Delete associated PolicyFieldRules
  await db.deleteFrom("PolicyFieldRule").where("auditPolicyId", "=", policyId).execute();

  // 4. Delete AuditPolicy
  await db.deleteFrom("AuditPolicy").where("id", "=", policyId).execute();

  return ok({ policyId });
}
