import { NextRequest, NextResponse } from "next/server";
import { verifyNIN } from "@/utils/monnify";
import { getServerSession } from "next-auth";
import { authOptions } from "@/auth";
import { User } from "@/models/user";
import dbConnect from "@/lib/connectdb";

export async function POST(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    if (!session || !session.user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    const email = session.user?.email;
    await dbConnect();

    const body = await req.json();
    const { nin } = body;

    // Check if email is provided
    if (!email) {
      return NextResponse.json({ error: "Email is required" }, { status: 400 });
    }

    // Find the user by email
    const user = await User.findOne({ email });
    if (!user) {
      return NextResponse.json({ error: "User not found" }, { status: 404 });
    }

    // Check if user already has a NIN submitted
    if (user.nin && user.nin.trim() !== "") {
      return NextResponse.json(
        {
          success: true,
          message: "NIN already submitted",
          nin: user.nin,
        },
        { status: 200 }
      );
    }

    // If no NIN is provided in the request
    if (!nin) {
      return NextResponse.json({ error: "NIN is required" }, { status: 400 });
    }

    // Verify the NIN
    const result = await verifyNIN(nin);

    // If verification is successful, save the NIN to the user's profile
    if (result.success) {
      user.nin = nin;
      await user.save();
    }

    return NextResponse.json(result, { status: 200 });
  } catch (error) {
    console.error("Error verifying NIN:", error);
    return NextResponse.json(
      {
        error: "Internal Server Error",
        details:
          error instanceof Error ? error.message : "An unknown error occurred",
        stack:
          process.env.NODE_ENV === "development"
            ? error instanceof Error
              ? error.stack
              : null
            : undefined,
      },
      { status: 500 }
    );
  }
}
