import crypto from "crypto";
import type { PrismaClient } from "@prisma/client";
import { sendTwoFactorEmail } from "./smtp.js";

const MINUTES_VALID = 10;

function sha256Hex(input: string): string {
  return crypto.createHash("sha256").update(input, "utf8").digest("hex");
}

function randomSixDigit(): string {
  return String(crypto.randomInt(100_000, 1_000_000));
}

export async function issueEmailChallengeAndSend(
  prisma: PrismaClient,
  userId: bigint,
  email: string,
  ip: string | undefined
): Promise<void> {
  const code = randomSixDigit();
  const tokenHash = sha256Hex(code);

  const expiresAt = new Date(Date.now() + MINUTES_VALID * 60_000);
  const created = await prisma.emailTwoFactorToken.create({
    data: {
      userId,
      tokenHash,
      expiresAt,
      sentToEmail: email,
      ipAddress: ip ?? null,
    },
    select: { id: true },
  });

  try {
    await sendTwoFactorEmail(prisma, email, code, MINUTES_VALID);
  } catch (err) {
    await prisma.emailTwoFactorToken.delete({ where: { id: created.id } }).catch(() => null);
    throw err;
  }

  if (process.env.NODE_ENV !== "production") {
    console.info(`[2FA] Email challenge issued for ${email} (${MINUTES_VALID} min).`);
  }
}

export async function verifyEmailChallenge(
  prisma: PrismaClient,
  userId: bigint,
  code: string
): Promise<{ ok: true } | { ok: false; reason: "expired" | "invalid" | "none" }> {
  const tokenHash = sha256Hex(code);
  const tok = await prisma.emailTwoFactorToken.findFirst({
    where: { userId, consumedAt: null, expiresAt: { gt: new Date() } },
    orderBy: { id: "desc" },
    select: { id: true, tokenHash: true },
  });
  if (!tok) return { ok: false, reason: "none" };
  if (tok.tokenHash !== tokenHash) return { ok: false, reason: "invalid" };

  await prisma.emailTwoFactorToken.update({
    where: { id: tok.id },
    data: { consumedAt: new Date() },
    select: { id: true },
  });
  return { ok: true };
}
