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 GetAuditEntryInput {
  id: string;
}

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

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

  if (auditEntry) {
    const scopeErr = checkScopeAuthorization(auditEntry.companyId, ctx);
    if (scopeErr) return scopeErr;
  }

  return ok({ auditEntry: auditEntry ?? null });
}

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;
}
