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

export interface GetChangeDetailsInput {
  auditEntryId: string;
}

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

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

  if (!entry) return err(new AuditEntryNotFoundError(input.auditEntryId));

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

  const changeDetails = await db
    .selectFrom("ChangeDetail")
    .selectAll()
    .where("auditEntryId", "=", input.auditEntryId)
    .execute();

  return ok({ changeDetails });
}

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