import { NextRequest, NextResponse } from "next/server";
import jwt from "jsonwebtoken";
import bcrypt from "bcryptjs";
import Cart from "@/models/Cart";
import Wishlist from "@/models/Wishlist";

import dbConnect from "@/lib/mongodb";
import User from "@/models/User";
// import UserType from "@/models/UserType";

const JWT_SECRET = process.env.JWT_SECRET!;

export async function POST(req: NextRequest) {
  try {
    await dbConnect();

    const body = await req.json();

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

    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 }
      );
    }

    const user = await User.findOne({ email });

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

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

    const isPasswordValid = await bcrypt.compare(
      password,
      user.password
    );

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

    const token = jwt.sign(
      {
        userId: user._id.toString(),
        email: user.email,
        roleId: user.role?._id,
      },
      JWT_SECRET,
      {
        expiresIn: "7d",
      }
    );
    if (guest_id) {
 
      
    const cartchange= await Cart.findOne({ guestId: guest_id });
    const wishlistchange= await Wishlist.findOne({ guestId: guest_id });
    if(cartchange){
      await Cart.updateMany({guestId: guest_id }, { user: user._id, guestId: null });
    }
    if(wishlistchange){
      await Wishlist.updateMany({ guestId: guest_id }, { user: user._id, guestId: null });
    }
  }
    const payload = {
      success: true,
      message: "Login successful",
      data: {
        token,
        expiresIn: "7d",
        user: {
          id: user._id,
          name: user.name,
          email: user.email,
          phone: user.phone,
          role: user.role,
          status: user.status,
        },
      },
    };

    const response = NextResponse.json(payload, { status: 200 });
    // Set cookies server-side so production builds receive them reliably
    const oneWeek = 60 * 60 * 24 * 7;
    response.cookies.set('clienttoken', token, { path: '/', maxAge: oneWeek });
    // response.cookies.set('token', token, { path: '/', maxAge: oneWeek });
    return response;
  } catch (error: any) {
    console.error("Login Error:", error);

    return NextResponse.json(
      {
        success: false,
        message: error?.message || "Login failed",
      },
      { status: 500 }
    );
  }
}