import type { Prisma, PrismaClient } from '@prisma/client';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { router, withPermission } from '../trpc';

/** A login belongs to one side or the other. The API already refuses a tenant
 * login every back-office procedure, so a staff role on one would be inert — but
 * it would read on the users screen as access that had been granted. */
async function assertRolesFitLogin(
  db: PrismaClient | Prisma.TransactionClient,
  tenantId: string | null,
  roleIds: string[],
): Promise<void> {
  if (!tenantId || roleIds.length === 0) return;
  const roles = await db.role.findMany({ where: { id: { in: roleIds } }, select: { code: true } });
  if (roles.some((r) => r.code !== 'TENANT')) {
    throw new TRPCError({ code: 'BAD_REQUEST', message: 'A tenant login can only hold the tenant role' });
  }
}

/** User + login administration (create staff or tenant logins, assign roles).
 * Gated on the admin-only `role` permission. */
export const usersRouter = router({
  list: withPermission('role.read').query(async ({ ctx }) => {
    const users = await ctx.prisma.user.findMany({
      where: { deletedAt: null },
      orderBy: { createdAt: 'asc' },
      include: {
        roles: { select: { role: { select: { id: true, code: true, name: true } } } },
        tenant: { select: { id: true, name: true } },
      },
    });
    return users.map((u) => ({
      id: u.id,
      email: u.email,
      name: u.name,
      isActive: u.isActive,
      tenantId: u.tenantId,
      tenantName: u.tenant?.name ?? null,
      roles: u.roles.map((r) => ({ id: r.role.id, code: r.role.code, name: r.role.name })),
    }));
  }),

  /** Tenants that don't yet have a login, for the "create tenant login" picker. */
  tenantsWithoutLogin: withPermission('role.read').query(({ ctx }) =>
    ctx.prisma.tenant.findMany({
      where: { organizationId: ctx.organizationId ?? undefined, deletedAt: null, users: { none: {} } },
      orderBy: { name: 'asc' },
      select: { id: true, name: true, email: true },
    }),
  ),

  create: withPermission('role.create')
    .input(
      z.object({
        email: z.string().email(),
        name: z.string().min(1),
        password: z.string().min(6),
        roleIds: z.array(z.string()),
        tenantId: z.string().optional().nullable(),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      const dup = await ctx.prisma.user.findUnique({ where: { email: input.email }, select: { id: true } });
      if (dup) throw new TRPCError({ code: 'BAD_REQUEST', message: 'A user with that email already exists' });
      await assertRolesFitLogin(ctx.prisma, input.tenantId || null, input.roleIds);
      const user = await ctx.prisma.user.create({
        data: {
          email: input.email,
          name: input.name,
          passwordHash: ctx.hashPassword(input.password),
          // Somebody else chose this one, so it has to be replaced before use.
          mustChangePassword: true,
          tenantId: input.tenantId || null,
          roles: { create: input.roleIds.map((roleId) => ({ roleId })) },
        },
      });
      return { id: user.id };
    }),

  update: withPermission('role.update')
    .input(
      z.object({
        id: z.string(),
        name: z.string().min(1),
        isActive: z.boolean(),
        roleIds: z.array(z.string()),
        newPassword: z.string().min(6).optional(),
      }),
    )
    .mutation(({ ctx, input }) =>
      ctx.prisma.$transaction(async (tx) => {
        const target = await tx.user.findUnique({ where: { id: input.id }, select: { tenantId: true } });
        if (!target) throw new TRPCError({ code: 'NOT_FOUND', message: 'User not found' });
        await assertRolesFitLogin(tx, target.tenantId, input.roleIds);
        await tx.user.update({
          where: { id: input.id },
          data: {
            name: input.name,
            isActive: input.isActive,
            // Resetting somebody else's password re-arms the gate; changing your
            // own here does not, since you chose it.
            ...(input.newPassword
              ? { passwordHash: ctx.hashPassword(input.newPassword), mustChangePassword: input.id !== ctx.user.id }
              : {}),
          },
        });
        await tx.userRole.deleteMany({ where: { userId: input.id } });
        if (input.roleIds.length) await tx.userRole.createMany({ data: input.roleIds.map((roleId) => ({ userId: input.id, roleId })) });
        return { id: input.id };
      }),
    ),
});
