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

export interface ActivateAuditPolicyInput {
  policyId: string;
}

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

  // 3. Check required fields
  if (!existing.entityName || !existing.operationType) {
    return err(new IncompletePolicyError(policyId));
  }

  // 4. Verify entity is still registered
  const entity = await db
    .selectFrom("AuditableEntity")
    .selectAll()
    .where("entityName", "=", existing.entityName)
    .executeTakeFirst();

  if (!entity) {
    return err(new EntityTypeNotRegisteredError(existing.entityName));
  }

  // 5. 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 });
}
