const Visitor = require("../../models/securityops/visitorModel");
const { errorResponse } = require("../../utils/errorResponseHandler");
const { logUserAction } = require("../../utils/userActionLogger");
const User = require("../../models/userModel");

const createVisitor = async (req, res) => {
  try {
    const {
      visitorName,
      phoneNumber,
      company,
      vehicleNumber,
      hostId,
      purpose,
      parkingAllocation,
    } = req.body;

    const hostUser = await User.findById(hostId);

    //   if (!hostUser) {
    //   return res.status(404).json({
    //     success: false,
    //     message: "Host user not found",
    //   });
    // }

    // simple validation
    if (!visitorName || !phoneNumber) {
      return errorResponse(
        res,
        "Visitor name, phone number and host are required",
        400,
      );
    }

    const photo = req.file ? req.file.path : null;

    const visitor = new Visitor({
      photo,
      visitorName,
      phoneNumber,
      company,
      vehicleNumber,
      hostId,
      // hostId = hostUser._id,
      hostDetails: {
        id: hostUser._id,
        name: hostUser.name,
      },
      purpose,
      parkingAllocation,
      createdBy: req.user?._id,
      updatedBy: req.user?._id,
    });

    await visitor.save();

    // log action
    // await logUserAction({
    //   userId: req.user?._id,
    //   action: "CREATE_VISITOR",
    //   description: `Visitor ${visitorName} registered`,
    //   ip: req.ip
    // });

    return res.status(201).json({
      success: true,
      message: "Visitor registered successfully",
      data: visitor,
    });
  } catch (error) {
    console.error("Create Visitor Error:", error);
    return errorResponse(res, "Failed to register visitor", 500);
  }
};

const getVisitors = async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;

    const skip = (page - 1) * limit;

    const visitors = await Visitor.find({ isDeleted: false })
      .populate("hostId", "firstName")
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(limit);

    const total = await Visitor.countDocuments({ isDeleted: false });

    // await logUserAction({
    //   userId: req.user?._id,
    //   action: "VIEW_VISITORS",
    //   description: "Viewed visitor list",
    //   ip: req.ip
    // });

    return res.status(200).json({
      success: true,
      data: visitors,
      pagination: {
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit),
      },
    });
  } catch (error) {
    console.error("Get Visitors Error:", error);
    return errorResponse(res, "Failed to fetch visitors", 500);
  }
};

const approveVisitor = async (req, res) => {
  try {
    const { id } = req.params;

    const visitor = await Visitor.findOne({
      _id: id,
      isDeleted: false,
    });

    if (!visitor) {
      return errorResponse(res, "Visitor not found", 404);
    }

    // prevent approving twice
    if (visitor.hostApproval === "Approved") {
      return errorResponse(res, "Visitor already approved", 400);
    }

    visitor.hostApproval = "Approved";
    visitor.gateStatus = "Inside";
    visitor.updatedBy = req.user?._id;

    await visitor.save();

    await logUserAction({
      userId: req.user?._id,
      action: "APPROVE_VISITOR",
      description: `Visitor ${visitor.visitorName} approved`,
      ip: req.ip,
    });

    return res.status(200).json({
      success: true,
      message: "Visitor approved successfully",
      data: visitor,
    });
  } catch (error) {
    console.error("Approve Visitor Error:", error);
    return errorResponse(res, "Failed to approve visitor", 500);
  }
};

const markVisitorExit = async (req, res) => {
  try {
    const { id } = req.params;

    const visitor = await Visitor.findOne({
      _id: id,
      isDeleted: false,
    });

    if (!visitor) {
      return errorResponse(res, "Visitor not found", 404);
    }

    // Prevent exit if not approved
    if (visitor.hostApproval !== "Approved") {
      return errorResponse(res, "Visitor not approved yet", 400);
    }

    // Prevent duplicate exit
    if (visitor.gateStatus === "Exited") {
      return errorResponse(res, "Visitor already exited", 400);
    }

    visitor.gateStatus = "Exited";
    visitor.exitTime = new Date();
    visitor.updatedBy = req.user?._id;

    await visitor.save();

    await logUserAction({
      userId: req.user?._id,
      action: "VISITOR_EXIT",
      description: `Visitor ${visitor.visitorName} marked as exited`,
      ip: req.ip,
    });

    return res.status(200).json({
      success: true,
      message: "Visitor exit recorded successfully",
      data: visitor,
    });
  } catch (error) {
    console.error("Mark Exit Error:", error);
    return errorResponse(res, "Failed to mark visitor exit", 500);
  }
};

const deleteVisitor = async (req, res) => {
  try {
    const { id } = req.params;

    const visitor = await Visitor.findOne({
      _id: id,
      isDeleted: false,
    });

    if (!visitor) {
      return res.status(404).json({
        success: false,
        message: "Visitor not found",
      });
    }

    // Production Logic
    if (visitor.gateStatus === "Inside") {
      return res.status(400).json({
        success: false,
        message: "Visitor is inside. Mark exit before delete.",
      });
    }

    visitor.isDeleted = true;
    visitor.updatedBy = req.user?.id;

    await visitor.save();

    return res.json({
      success: true,
      message: "Visitor deleted successfully",
    });
  } catch (error) {
    console.log(error);
    return res.status(500).json({
      success: false,
      message: "Delete failed",
    });
  }
};

const getVisitorById = async (req, res) => {
  try {
    const { id } = req.params;


    const visitor = await Visitor.findOne({
      _id: id,
      isDeleted: false,
    })
      .populate("hostId", "firstName lastName email")
      .lean();

    if (!visitor) {
      return errorResponse(res, "Visitor not found", 404);
    }

    return res.status(200).json({
      success: true,
      data: visitor,
    });
  } catch (error) {
    console.error("Get Visitor By Id Error:", error);
    return errorResponse(res, "Failed to fetch visitor", 500);
  }
};

module.exports = {
  createVisitor,
  getVisitors,
  approveVisitor,
  markVisitorExit,
  deleteVisitor,
  getVisitorById,
};
