import { createHash, randomBytes } from "crypto";
import { prisma } from "@pmap/database";
import { getAdminSessionFromRequest } from "../../../../../../auth";
import { fail, ok } from "../../../../_lib";

function hashToken(token: string) {
  return createHash("sha256").update(token).digest("hex");
}

export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {
  try {
    if (!await getAdminSessionFromRequest(request)) return fail(request, "UNAUTHORIZED", "Admin login is required.", 401);
    const { id } = await params;
    const participant = await prisma.participantProfile.findUnique({
      where: { id },
      include: { user: { select: { id: true, email: true } } }
    });
    if (!participant) return fail(request, "PARTICIPANT_NOT_FOUND", "Participant could not be found.", 404);

    const token = randomBytes(32).toString("hex");
    const expiresAt = new Date(Date.now() + 1000 * 60 * 60 * 24);
    await prisma.passwordResetToken.create({
      data: {
        userId: participant.user.id,
        tokenHash: hashToken(token),
        expiresAt
      }
    });

    const resetUrl = new URL(`/reset-password?token=${token}`, request.url).toString();
    const template = await prisma.notificationTemplate.upsert({
      where: { code: "PARTICIPANT_PASSWORD_RESET" },
      update: {
        channel: "EMAIL",
        subject: "Reset your PMAP Annual Conference password",
        body: "Use the password reset link to set a new password for your participant account.",
        active: true
      },
      create: {
        code: "PARTICIPANT_PASSWORD_RESET",
        channel: "EMAIL",
        subject: "Reset your PMAP Annual Conference password",
        body: "Use the password reset link to set a new password for your participant account.",
        active: true
      }
    });
    const hasSmtpConfig = Boolean(process.env.SMTP_HOST && process.env.SMTP_FROM_EMAIL);

    await prisma.notificationLog.create({
      data: {
        templateId: template.id,
        channel: "EMAIL",
        recipient: participant.user.email,
        status: hasSmtpConfig ? "QUEUED" : "LOGGED",
        providerRef: hasSmtpConfig ? null : `local-password-reset-${participant.registrationReference}`,
        failureReason: hasSmtpConfig ? null : `SMTP is not configured. Password reset link was logged locally: ${resetUrl}`,
        sentAt: hasSmtpConfig ? null : new Date()
      }
    });

    console.info("Participant password reset email prepared", {
      to: participant.user.email,
      reference: participant.registrationReference,
      resetUrl,
      expiresAt: expiresAt.toISOString(),
      delivery: hasSmtpConfig ? "queued" : "logged"
    });

    return ok(request, {
      email: participant.user.email,
      expiresAt: expiresAt.toISOString(),
      delivery: hasSmtpConfig ? "queued" : "logged"
    });
  } catch (error) {
    return fail(request, "PASSWORD_RESET_FAILED", "Password reset link could not be generated.", 500, error instanceof Error ? error.message : error);
  }
}
