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

export interface GetAuditPolicyInput {
  id: string;
}

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

  const policy = await db
    .selectFrom("AuditPolicy")
    .selectAll()
    .where("id", "=", input.id)
    .executeTakeFirst();

  if (!policy) return ok({ policy: null, fieldRules: [] });

  const scopeErr = checkScopeAuthorization(policy.companyId, ctx);
  if (scopeErr) return scopeErr;

  const fieldRules = await db
    .selectFrom("PolicyFieldRule")
    .selectAll()
    .where("auditPolicyId", "=", policy.id)
    .execute();

  return ok({ policy, fieldRules });
}

function checkScopeAuthorization(entityCompanyId: string | null, ctx: QueryContext) {
  if (ctx.companyId === undefined) return null;
  if (ctx.companyId === null && entityCompanyId !== null) {
    return err(new UnauthorizedError(ctx.actorId));
  }
  if (ctx.companyId !== null && entityCompanyId !== ctx.companyId) {
    return err(new UnauthorizedError(ctx.actorId));
  }
  return null;
}
