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,
  ConflictingActivePolicyError,
  UnauthorizedError,
} from "../lib/errors.generated";

export interface ReactivateAuditPolicyInput {
  policyId: string;
}

/**
 * Function: reactivateAuditPolicy
 *
 * Transitions an audit policy from INACTIVE back to ACTIVE status, resuming
 * audit capture for the specified entity, operation type, and scope.
 * Reactivation is rejected if a conflicting ACTIVE policy already exists for
 * the same (entityName, companyId, operationType) combination.
 */
export async function run(db: Transaction, input: ReactivateAuditPolicyInput, 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, "reactivate");
  if (!nextStatus) {
    return err(new InvalidStateError(policyId));
  }

  // 3. Check for conflicting ACTIVE policy (forUpdate to prevent concurrent activations)
  const conflicting = await db
    .selectFrom("AuditPolicy")
    .selectAll()
    .where("entityName", "=", existing.entityName)
    .where("companyId", existing.companyId ? "=" : "is", existing.companyId)
    .where("operationType", "=", existing.operationType)
    .where("status", "=", "ACTIVE")
    .forUpdate()
    .executeTakeFirst();

  if (conflicting) {
    return err(new ConflictingActivePolicyError(policyId));
  }

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

  return ok({ policy });
}
