import { NextResponse } from "next/server";
import bcrypt from "bcryptjs";
import { prisma } from "@/lib/prisma";
import { hashPasswordResetToken } from "@/lib/password-reset";

type ResetPasswordBody = {
  email?: string;
  token?: string;
  password?: string;
};

export async function POST(request: Request) {
  try {
    const body = (await request.json()) as ResetPasswordBody;
    const email = body.email?.toLowerCase().trim() ?? "";
    const token = body.token?.trim() ?? "";
    const password = body.password ?? "";

    if (!email || !token || password.length < 8) {
      return NextResponse.json({ error: "Invalid payload." }, { status: 400 });
    }

    const tokenHash = hashPasswordResetToken(token);

    const resetRecord = await prisma.passwordResetToken.findFirst({
      where: {
        email,
        tokenHash,
        usedAt: null,
        expiresAt: { gt: new Date() },
      },
    });

    if (!resetRecord) {
      return NextResponse.json({ error: "Reset token is invalid or expired." }, { status: 400 });
    }

    const user = await prisma.user.findUnique({
      where: { email },
      select: { id: true },
    });

    if (!user) {
      return NextResponse.json({ error: "User not found." }, { status: 404 });
    }

    const passwordHash = await bcrypt.hash(password, 12);

    await prisma.$transaction(async (tx) => {
      await tx.user.update({
        where: { id: user.id },
        data: { passwordHash },
      });

      await tx.passwordResetToken.update({
        where: { id: resetRecord.id },
        data: { usedAt: new Date() },
      });

      await tx.passwordResetToken.deleteMany({
        where: {
          email,
          usedAt: null,
        },
      });
    });

    return NextResponse.json({ ok: true });
  } catch (error) {
    console.error("reset-password failed", error);
    return NextResponse.json({ error: "No se pudo actualizar la contrasena." }, { status: 500 });
  }
}
