import { NextRequest, NextResponse } from "next/server";
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import { prisma } from "@/lib/prisma";

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();

    const email = body.email?.trim().toLowerCase();
    const password = body.password;

    // ------------------------
    // Validation
    // ------------------------

    if (!email) {
      return NextResponse.json(
        {
          success: false,
          message: "Email is required.",
        },
        { status: 400 }
      );
    }

    if (!password) {
      return NextResponse.json(
        {
          success: false,
          message: "Password is required.",
        },
        { status: 400 }
      );
    }

    // ------------------------
    // Find Student
    // ------------------------

    const student = await prisma.students.findUnique({
      where: {
        email,
      },
    });

    if (!student) {
      return NextResponse.json(
        {
          success: false,
          message: "Invalid email or password.",
        },
        { status: 401 }
      );
    }

    // ------------------------
    // Verify Password
    // ------------------------

    const passwordMatched = await bcrypt.compare(
      password,
      student.password
    );

    if (!passwordMatched) {
      return NextResponse.json(
        {
          success: false,
          message: "Invalid email or password.",
        },
        { status: 401 }
      );
    }

    // ------------------------
    // Check verification & status
    // ------------------------

    if (!student.email_verified) {
      return NextResponse.json(
        {
          success: false,
          message: "Please verify your email before logging in.",
        },
        { status: 403 }
      );
    }

    if (student.status !== "active") {
      return NextResponse.json(
        {
          success: false,
          message: "Your account is inactive. Please contact admin.",
        },
        { status: 403 }
      );
    }

    // ------------------------
    // Generate JWT
    // ------------------------

    const token = jwt.sign(
      {
        id: student.id,
        student_id: student.student_id,
        name: student.name,
        email: student.email,
      },
      process.env.JWT_SECRET!,
      {
        expiresIn: "7d",
      }
    );

    // ------------------------
    // Response
    // ------------------------

    const response = NextResponse.json({
      success: true,
      message: "Login successful.",
      data: {
        id: student.id,
        student_id: student.student_id,
        name: student.name,
        email: student.email,
      },
    });

    response.cookies.set({
      name: "student_token",
      value: token,
      httpOnly: true,
      // secure: process.env.NODE_ENV === "production",
      secure: false,
      sameSite: "lax",
      path: "/",
      maxAge: 60 * 60 * 24 * 7, // 7 days
    });

    return response;
  } catch (error) {
    console.error("Student Login Error:", error);

    return NextResponse.json(
      {
        success: false,
        message: "Something went wrong.",
      },
      {
        status: 500,
      }
    );
  }
}