import { createHash, randomBytes } from 'node:crypto';
import { AccountInviteKind, Prisma } from '@prisma/client';
import { prismaUnscoped } from '../../lib/prisma';
import { publicWebUrl } from '../../config/env';
import { hashPassword } from '../../lib/password';
import { BadRequestError, ForbiddenError, NotFoundError } from '../../lib/errors';

/**
 * One-time links that let a CRM user set their password.
 *
 * The super admin never types anyone's password: a new CRM user gets an
 * INVITE link, and a CRM user who is locked out gets a RESET link. The token
 * is 32 random bytes; only its SHA-256 is stored, so the table alone opens
 * nothing. Only the newest link per user works — issuing one deletes any
 * unused older one.
 */

export const INVITE_HOURS = 72;
export const RESET_HOURS = 2;

const TOKEN_RE = /^[A-Za-z0-9_-]{43}$/;

export const hashToken = (token: string) => createHash('sha256').update(token).digest('hex');

export const inviteUrl = (token: string) => `${publicWebUrl}/crm/invite/${token}`;

type Client = Prisma.TransactionClient | typeof prismaUnscoped;

/** Mint a link for `userId`, retiring any unused earlier one. Returns the raw token. */
export async function issueInvite(client: Client, userId: string, kind: AccountInviteKind, createdById: string | null) {
  const token = randomBytes(32).toString('base64url');
  const hours = kind === AccountInviteKind.INVITE ? INVITE_HOURS : RESET_HOURS;
  const expiresAt = new Date(Date.now() + hours * 60 * 60 * 1000);
  await client.accountInvite.deleteMany({ where: { userId, usedAt: null } });
  await client.accountInvite.create({ data: { userId, kind, tokenHash: hashToken(token), expiresAt, createdById } });
  return { token, expiresAt, hours };
}

/** Find a link that can still be used, or say exactly why not. */
async function usableInvite(token: string) {
  if (!TOKEN_RE.test(token)) throw new NotFoundError('This link is not valid. Ask for a new one.', 'INVITE_INVALID');
  const invite = await prismaUnscoped.accountInvite.findUnique({
    where: { tokenHash: hashToken(token) },
    include: { user: { select: { id: true, name: true, email: true, deactivatedAt: true } } },
  });
  if (!invite) throw new NotFoundError('This link is not valid. Ask for a new one.', 'INVITE_INVALID');
  if (invite.usedAt) {
    throw new BadRequestError('This link has already been used. Sign in with your password, or ask for a new link.', 'INVITE_USED');
  }
  if (invite.expiresAt.getTime() < Date.now()) {
    throw new BadRequestError('This link has expired. Ask the super admin for a new one.', 'INVITE_EXPIRED');
  }
  if (invite.user.deactivatedAt) {
    throw new ForbiddenError('This account has been switched off. Contact your administrator.', 'ACCOUNT_DEACTIVATED');
  }
  return invite;
}

/** What the set-password page shows before the user types anything. */
export async function lookupInvite(token: string) {
  const invite = await usableInvite(token);
  return { name: invite.user.name, email: invite.user.email, kind: invite.kind, expiresAt: invite.expiresAt };
}

/**
 * Set the password and burn the link. Stamps passwordChangedAt, so on a RESET
 * every session that predates the new password ends at its next refresh.
 */
export async function acceptInvite(token: string, password: string) {
  const invite = await usableInvite(token);
  const passwordHash = await hashPassword(password);
  const email = await prismaUnscoped.$transaction(async (tx) => {
    // Single use, even when two tabs submit at once.
    const claimed = await tx.accountInvite.updateMany({
      where: { id: invite.id, usedAt: null, expiresAt: { gt: new Date() } },
      data: { usedAt: new Date() },
    });
    if (claimed.count !== 1) {
      throw new BadRequestError('This link has already been used. Sign in with your password, or ask for a new link.', 'INVITE_USED');
    }
    const user = await tx.user.update({
      where: { id: invite.userId },
      data: { passwordHash, passwordChangedAt: new Date() },
      select: { email: true },
    });
    await tx.accountInvite.deleteMany({ where: { userId: invite.userId, usedAt: null } });
    return user.email;
  });
  return { email };
}
