import { NextResponse } from "next/server";
import { z } from "zod";

import {
  consumePasswordResetToken
} from "@/features/auth/lib/password-reset";
import { hashPassword } from "@/lib/auth";
import { createAuditTrailSafe } from "@/lib/audit-trail";
import { prisma } from "@/lib/prisma";

const resetPasswordSchema = z
  .object({
    token: z.string().min(1, "Token wajib diisi"),
    password: z.string().min(8, "Password minimal 8 karakter"),
    password_confirmation: z.string().min(8, "Konfirmasi password minimal 8 karakter")
  })
  .refine((value) => value.password === value.password_confirmation, {
    message: "Konfirmasi password tidak sama",
    path: ["password_confirmation"]
  });

export async function POST(request: Request) {
  try {
    const parsed = resetPasswordSchema.safeParse(await request.json());
    if (!parsed.success) {
      return NextResponse.json(
        {
          message: "Validasi gagal",
          errors: parsed.error.flatten().fieldErrors
        },
        { status: 422 }
      );
    }

    const resetToken = await consumePasswordResetToken(parsed.data.token);
    if (!resetToken) {
      return NextResponse.json(
        {
          message: "Token reset password tidak valid atau sudah kedaluwarsa."
        },
        { status: 400 }
      );
    }

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

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

    await createAuditTrailSafe({
      userId: resetToken.userId,
      action: "PASSWORD_RESET_COMPLETED",
      entityType: "AUTH",
      entityId: resetToken.userId,
      method: request.method,
      pathname: new URL(request.url).pathname,
      statusCode: 200,
      summary: "Password berhasil direset"
    });

    return NextResponse.json({
      message: "Password berhasil direset. Silakan login kembali."
    });
  } catch (error) {
    return NextResponse.json(
      {
        message: error instanceof Error ? error.message : "Gagal reset password"
      },
      { status: 500 }
    );
  }
}
