import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { ENFORCED_PERMISSIONS, router, withPermission } from '../trpc';

/** Role + permission administration. Gated on the admin-only `role` permission. */
export const rolesRouter = router({
  list: withPermission('role.read').query(async ({ ctx }) => {
    const roles = await ctx.prisma.role.findMany({
      orderBy: { code: 'asc' },
      include: {
        permissions: { select: { permission: { select: { key: true } } } },
        _count: { select: { users: true } },
      },
    });
    return roles.map((r) => ({
      id: r.id,
      code: r.code,
      name: r.name,
      nameZh: r.nameZh,
      isSystem: r.isSystem,
      userCount: r._count.users,
      permissionKeys: r.permissions.map((p) => p.permission.key),
    }));
  }),

  /** The permissions worth offering in the role editor: the ones some procedure
   *  actually checks, plus anything already granted to a role so an existing
   *  grant never becomes invisible. The seed creates four actions per resource
   *  regardless, which otherwise fills the grid with checkboxes that do nothing. */
  permissions: withPermission('role.read').query(async ({ ctx }) => {
    const [all, granted] = await Promise.all([
      ctx.prisma.permission.findMany({ orderBy: { key: 'asc' }, select: { key: true, description: true } }),
      ctx.prisma.rolePermission.findMany({ select: { permission: { select: { key: true } } } }),
    ]);
    const inUse = new Set(granted.map((g) => g.permission.key));
    return all.filter((p) => ENFORCED_PERMISSIONS.has(p.key) || inUse.has(p.key));
  }),

  upsert: withPermission('role.update')
    .input(
      z.object({
        id: z.string().optional(),
        code: z.string().min(1).regex(/^[A-Z0-9_]+$/, 'Use A–Z, 0–9 and _ for the code'),
        name: z.string().min(1),
        nameZh: z.string().optional().nullable(),
        permissionKeys: z.array(z.string()),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      const perms = await ctx.prisma.permission.findMany({ where: { key: { in: input.permissionKeys } }, select: { id: true } });
      return ctx.prisma.$transaction(async (tx) => {
        let roleId: string;
        if (input.id) {
          const existing = await tx.role.findUnique({ where: { id: input.id }, select: { id: true, code: true } });
          if (!existing) throw new TRPCError({ code: 'NOT_FOUND' });
          // The portal role, by definition, holds nothing from the back office.
          // The API refuses a tenant login either way, so this stops a role that
          // looks like it grants access but silently cannot.
          if (existing.code === 'TENANT' && input.permissionKeys.length) {
            throw new TRPCError({ code: 'BAD_REQUEST', message: 'The tenant role cannot be granted back-office permissions' });
          }
          // Code is immutable once created; name + permissions are editable (system roles too).
          await tx.role.update({ where: { id: input.id }, data: { name: input.name, nameZh: input.nameZh ?? null } });
          roleId = input.id;
          await tx.rolePermission.deleteMany({ where: { roleId } });
        } else {
          const dup = await tx.role.findUnique({ where: { code: input.code }, select: { id: true } });
          if (dup) throw new TRPCError({ code: 'BAD_REQUEST', message: 'A role with that code already exists' });
          const created = await tx.role.create({ data: { code: input.code, name: input.name, nameZh: input.nameZh ?? null, isSystem: false } });
          roleId = created.id;
        }
        if (perms.length) await tx.rolePermission.createMany({ data: perms.map((p) => ({ roleId, permissionId: p.id })) });
        return { id: roleId };
      });
    }),

  remove: withPermission('role.delete')
    .input(z.object({ id: z.string() }))
    .mutation(async ({ ctx, input }) => {
      const role = await ctx.prisma.role.findUnique({ where: { id: input.id }, select: { isSystem: true, _count: { select: { users: true } } } });
      if (!role) throw new TRPCError({ code: 'NOT_FOUND' });
      if (role.isSystem) throw new TRPCError({ code: 'BAD_REQUEST', message: 'A system role cannot be deleted' });
      if (role._count.users > 0) throw new TRPCError({ code: 'BAD_REQUEST', message: 'Remove users from this role before deleting it' });
      await ctx.prisma.role.delete({ where: { id: input.id } });
      return { id: input.id };
    }),
});
