import type { Prisma } from '@prisma/client';
import type { DashboardAccessRule } from '@nexumi/shared';
import { prisma } from './prisma';

export async function listAccessRules(guildId: string): Promise<DashboardAccessRule[]> {
  const rules = await prisma.dashboardAccessRule.findMany({
    where: { guildId },
    orderBy: { createdAt: 'asc' }
  });

  return rules.map((rule) => ({
    id: rule.id,
    roleId: rule.roleId,
    modules: rule.modules as DashboardAccessRule['modules']
  }));
}

export async function replaceAccessRules(
  guildId: string,
  rules: DashboardAccessRule[]
): Promise<DashboardAccessRule[]> {
  await prisma.guild.upsert({ where: { id: guildId }, update: {}, create: { id: guildId } });

  await prisma.$transaction([
    prisma.dashboardAccessRule.deleteMany({ where: { guildId } }),
    ...rules.map((rule) =>
      prisma.dashboardAccessRule.create({
        data: {
          guildId,
          roleId: rule.roleId,
          modules: rule.modules as Prisma.InputJsonValue
        }
      })
    )
  ]);

  return listAccessRules(guildId);
}
