import { createAuditEntry } from "../lib/audit.js";
import type { TRPCContext } from "../trpc.js";
import { invalidateRoleDefaultsCache } from "../trpc.js";
import {
  buildSystemRoleConfigUpdateData,
  systemRoleConfigUpdateInputSchema,
  type SystemRoleConfigUpdateInput,
} from "./system-role-config-support.js";

type SystemRoleConfigProcedureContext = Pick<TRPCContext, "db" | "dbUser">;

export { systemRoleConfigUpdateInputSchema };

export async function listSystemRoleConfigs(
  ctx: SystemRoleConfigProcedureContext,
) {
  return ctx.db.systemRoleConfig.findMany({
    orderBy: { sortOrder: "asc" },
  });
}

export async function updateSystemRoleConfig(
  ctx: SystemRoleConfigProcedureContext,
  input: SystemRoleConfigUpdateInput,
) {
  const existing = await ctx.db.systemRoleConfig.findUnique({
    where: { role: input.role as never },
  });

  const result = await ctx.db.systemRoleConfig.update({
    where: { role: input.role as never },
    data: buildSystemRoleConfigUpdateData(input),
  });

  invalidateRoleDefaultsCache();

  void createAuditEntry({
    db: ctx.db,
    entityType: "SystemRoleConfig",
    entityId: input.role,
    entityName: result.label,
    action: "UPDATE",
    ...(ctx.dbUser?.id ? { userId: ctx.dbUser.id } : {}),
    before: (existing ?? {}) as unknown as Record<string, unknown>,
    after: result as unknown as Record<string, unknown>,
    source: "ui",
  });

  return result;
}
