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

/**
 * What a logged-in person can do to their own account, whoever they are.
 *
 * Deliberately on protectedProcedure and not behind a permission: until now the
 * only writers of a password hash were users.create and users.update, both
 * gated on role.update, so nobody could change their own password unless they
 * held an admin-level grant — and a tenant handed credentials by the office
 * could never change them at all, leaving staff knowing every tenant's password
 * because staff typed it.
 *
 * It also has to stay reachable while mustChangePassword is set, which is
 * exactly why the two middlewares carry that gate rather than protectedProcedure.
 *
 * Note this does not end other sessions: nothing in this system tracks or
 * revokes an issued token (see auth.service.refresh). Changing a password stops
 * the old one being usable to sign in; it does not sign anyone out.
 */
export const accountRouter = router({
  changePassword: protectedProcedure
    .input(
      z.object({
        currentPassword: z.string().min(1),
        // Same floor as users.create, so a password set here is no weaker than
        // one an administrator sets.
        newPassword: z.string().min(6),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      // verifyAndLoad read this row microseconds ago in the same request, so a
      // miss is a broken invariant rather than something the caller did.
      const user = await ctx.prisma.user.findUniqueOrThrow({
        where: { id: ctx.user.id },
        select: { passwordHash: true },
      });
      if (!ctx.verifyPassword(input.currentPassword, user.passwordHash)) {
        // BAD_REQUEST, never UNAUTHORIZED: the clients treat UNAUTHORIZED as an
        // expired session and sign the user out, so a typo would eject them.
        throw new TRPCError({ code: 'BAD_REQUEST', message: 'Current password is incorrect' });
      }
      if (ctx.verifyPassword(input.newPassword, user.passwordHash)) {
        throw new TRPCError({ code: 'BAD_REQUEST', message: 'The new password must be different from the current one' });
      }
      await ctx.prisma.user.update({
        where: { id: ctx.user.id },
        data: { passwordHash: ctx.hashPassword(input.newPassword), mustChangePassword: false },
      });
      return { ok: true };
    }),
});
