import {
  ok,
  err,
  requirePermission,
  type ReadonlyDB,
  type QueryContext,
  type PaginationInput,
  buildPaginatedResult,
  DEFAULT_PAGE_SIZE,
} from "@tailor-platform/erp-kit/core";
import type { AuditPolicyStatus } from "../db/auditPolicy.lifecycle.generated";
import type { DB } from "../generated/kysely-tailordb";
import { UnauthorizedError } from "../lib/errors.generated";

type PolicyOrderByField = "entityName" | "status" | "operationType" | "createdAt";

export interface ListAuditPoliciesInput extends PaginationInput<PolicyOrderByField> {
  entityName?: string;
  status?: AuditPolicyStatus;
  companyId?: string | null;
  operationType?: string;
}

export async function run(db: ReadonlyDB<DB>, input: ListAuditPoliciesInput, ctx: QueryContext) {
  const permCheck = requirePermission(ctx, "audit:audit:manageAuditPolicies");
  if (!permCheck.ok) return permCheck;

  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = input.orderBy ?? "id";
  const orderDirection = input.orderDirection ?? "asc";

  let query = db.selectFrom("AuditPolicy").selectAll();

  if (input.entityName) query = query.where("entityName", "=", input.entityName);
  if (input.status) query = query.where("status", "=", input.status);
  if (input.operationType) query = query.where("operationType", "=", input.operationType);

  // Apply company-scope filtering from context
  if (ctx.companyId !== undefined) {
    // Reject out-of-scope requests
    if (input.companyId !== undefined) {
      if (ctx.companyId === null && input.companyId !== null) {
        return err(new UnauthorizedError(ctx.actorId));
      }
      if (ctx.companyId !== null && input.companyId !== ctx.companyId) {
        return err(new UnauthorizedError(ctx.actorId));
      }
    }
    // Apply context scope restriction
    if (ctx.companyId === null) {
      query = query.where("companyId", "is", null);
    } else {
      query = query.where("companyId", "=", ctx.companyId);
    }
  } else if (input.companyId !== undefined) {
    // No scope restriction from context; apply input filter if provided
    if (input.companyId === null) {
      query = query.where("companyId", "is", null);
    } else {
      query = query.where("companyId", "=", input.companyId);
    }
  }

  const policies = await query
    .orderBy(orderBy, orderDirection)
    .limit(limit + 1)
    .offset(offset)
    .execute();

  const paginatedResult = buildPaginatedResult(policies, limit);

  // Load field rules for all policies in the current page
  const policyIds = paginatedResult.items.map((p) => p.id);
  const fieldRules =
    policyIds.length > 0
      ? await db
          .selectFrom("PolicyFieldRule")
          .selectAll()
          .where("auditPolicyId", "in", policyIds)
          .execute()
      : [];

  // Map field rules onto each policy
  const fieldRulesByPolicyId = new Map<string, (typeof fieldRules)[number][]>();
  for (const rule of fieldRules) {
    const existing = fieldRulesByPolicyId.get(rule.auditPolicyId) ?? [];
    existing.push(rule);
    fieldRulesByPolicyId.set(rule.auditPolicyId, existing);
  }

  const items = paginatedResult.items.map((policy) => ({
    policy,
    fieldRules: fieldRulesByPolicyId.get(policy.id) ?? [],
  }));

  return ok({
    items,
    hasNextPage: paginatedResult.hasNextPage,
  });
}
