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

export const systemRoleConfigRouter = createTRPCRouter({
  /** List all role configs (sorted by sortOrder) */
  list: adminProcedure.query(async ({ ctx }) => {
    return ctx.db.systemRoleConfig.findMany({
      orderBy: { sortOrder: "asc" },
    });
  }),

  /** Update a role's default permissions, label, description, and color */
  update: adminProcedure
    .input(systemRoleConfigUpdateInputSchema)
    .mutation(async ({ ctx, input }) => {
      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),
      });

      // Invalidate cached role defaults so changes take effect immediately
      invalidateRoleDefaultsCache();

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

      return result;
    }),
});
