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

import {
  consumeEmailVerificationToken
} from "@/features/auth/lib/email-verification";
import { createAuditTrailSafe } from "@/lib/audit-trail";
import { prisma } from "@/lib/prisma";

const verifyEmailSchema = z.object({
  token: z.string().min(1, "Token wajib diisi")
});

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

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

    await prisma.$transaction(async (tx) => {
      await tx.user.update({
        where: { id: verificationToken.userId },
        data: {
          emailVerifiedAt: new Date()
        }
      });

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

    await createAuditTrailSafe({
      userId: verificationToken.userId,
      action: "EMAIL_VERIFIED",
      entityType: "AUTH",
      entityId: verificationToken.userId,
      method: request.method,
      pathname: new URL(request.url).pathname,
      statusCode: 200,
      summary: "Email berhasil diverifikasi"
    });

    return NextResponse.json({
      message: "Email berhasil diverifikasi. Silakan login."
    });
  } catch (error) {
    return NextResponse.json(
      {
        message: error instanceof Error ? error.message : "Gagal verifikasi email"
      },
      { status: 500 }
    );
  }
}
