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

import { sendPasswordResetEmail } from "@/features/auth/lib/auth-emails";
import { buildPasswordResetUrl, issuePasswordResetToken } from "@/features/auth/lib/password-reset";
import { createAuditTrailSafe } from "@/lib/audit-trail";
import { prisma } from "@/lib/prisma";

const forgotPasswordSchema = z.object({
  email: z.string().trim().email("Email tidak valid")
});

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

    const email = parsed.data.email.toLowerCase();
    const user = await prisma.user.findFirst({
      where: {
        email,
        status: "ACTIVE",
        emailVerifiedAt: {
          not: null
        }
      }
    });

    if (user?.email) {
      const { plainToken } = await issuePasswordResetToken(user.id);
      await sendPasswordResetEmail({
        to: user.email,
        name: user.name,
        resetUrl: buildPasswordResetUrl(plainToken)
      });

      await createAuditTrailSafe({
        userId: user.id,
        action: "PASSWORD_RESET_REQUESTED",
        entityType: "AUTH",
        entityId: user.id,
        method: request.method,
        pathname: new URL(request.url).pathname,
        statusCode: 200,
        summary: "Permintaan reset password dikirim"
      });
    }

    return NextResponse.json({
      message: "Jika email terdaftar, link reset password sudah dikirim."
    });
  } catch (error) {
    return NextResponse.json(
      {
        message: error instanceof Error ? error.message : "Gagal mengirim email reset password"
      },
      { status: 500 }
    );
  }
}
