const Organization = require("../../models/admin/orgModal");
const { errorResponse } = require("../../utils/errorResponseHandler");
const { logUserAction } = require("../../utils/userActionLogger");

// Create Organization
// const createOrg = async (req, res) => {
//   try {
//     const { orgName } = req.body;
//     if (!orgName) {
//       return errorResponse(res, "Organization name is required", 400);
//     }

//     const userId = req.user?._id;

//     // Check if organization with same name already exists
//     const existingOrg = await Organization.findOne({ orgName });
//     if (existingOrg) {
//       return errorResponse(res, "Organization name already exists", 409); // 409 = Conflict
//     }

//     const org = await Organization.create({
//       orgName,
//       createdBy: userId || null,
//       updatedBy: userId || null,
//     });

//     // Log user action
//     await logUserAction({
//       userId,
//       orgId: org._id,
//       action: "CREATE",
//       model: "Organization",
//       details: { orgId: org._id, orgName },
//       req,
//     });

//     res.status(201).json({ success: true, data: org });
//   } catch (error) {
//     return errorResponse(res, "Failed to create organization", 400, error);
//   }
// };
const createOrg = async (req, res) => {
  try {
    const { orgName, address, gstin } = req.body;
    const userId = req.user._id;

    //  Validate required fields
    if (!orgName || !address) {
      return errorResponse(
        res,
        "Organization name and address are required",
        400
      );
    }

    //  Prevent duplicates (case-insensitive)
    const existingOrg = await Organization.findOne({
      orgName: { $regex: `^${orgName}$`, $options: "i" },
      isDeleted: false,
    });

    if (existingOrg) {
      return errorResponse(res, "Organization name already exists", 409);
    }

    //  Create organization
    const org = await Organization.create({
      orgName: orgName.trim(),
      address: address.trim(),
      gstin: gstin?.trim() || null,
      createdBy: userId,
      updatedBy: userId,
    });

    //  Audit log
    await logUserAction({
      userId,
      orgId: org._id,
      action: "CREATE",
      model: "Organization",
      details: {
        orgId: org._id,
        orgName: org.orgName,
      },
      req,
    });

    return res.status(201).json({
      success: true,
      message: "Organization created successfully",
      data: org,
    });
  } catch (error) {
    console.error("Create Organization Error:", error);
    return errorResponse(res, "Failed to create organization", 500, error);
  }
};


// Get All Organizations with Pagination (exclude soft deleted)
const getOrgs = async (req, res) => {
  try {
    let { page = 1, limit = 10 } = req.query;
    page = parseInt(page);
    limit = parseInt(limit);
    const skip = (page - 1) * limit;

    const query = { isDeleted: false };

    const [orgs, total] = await Promise.all([
      Organization.find(query)
        .populate("createdBy", "firstName lastName email")
        .populate("updatedBy", "firstName lastName email")
        .skip(skip)
        .limit(limit)
        .sort({ createdAt: -1 }),
      Organization.countDocuments(query),
    ]);

    // Log user action
    await logUserAction({
      userId: req.user?._id,
      orgId: null,
      action: "READ",
      model: "Organization",
      details: { page, limit, count: orgs.length },
      req,
    });

    res.status(200).json({
      success: true,
      page,
      totalPages: Math.ceil(total / limit),
      totalRecords: total,
      data: orgs,
    });
  } catch (error) {
    return errorResponse(res, "Failed to fetch organizations", 500, error);
  }
};

// Get Organization by ID
const getOrgById = async (req, res) => {
  try {
    const org = await Organization.findById(req.params.id)
      .populate("createdBy", "firstName lastName email")
      .populate("updatedBy", "firstName lastName email");

    if (!org) return errorResponse(res, "Organization not found", 404);

    // Log user action
    await logUserAction({
      userId: req.user?._id,
      orgId: org._id,
      action: "READ",
      model: "Organization",
      details: { orgId: org._id },
      req,
    });

    res.status(200).json({ success: true, data: org });
  } catch (error) {
    return errorResponse(res, "Error fetching organization", 500, error);
  }
};

// Update Organization
const updateOrg = async (req, res) => {
  try {
    const { status } = req.body;
    const userId = req.user?._id;

    const org = await Organization.findByIdAndUpdate(
      req.params.id,
      { status, updatedBy: userId || null },
      { new: true, runValidators: true }
    );

    if (!org) return errorResponse(res, "Organization not found", 404);

    // Log user action
    await logUserAction({
      userId,
      orgId: org._id,
      action: "UPDATE",
      model: "Organization",
      details: { orgId: org._id, updatedFields: { status } },
      req,
    });

    res.status(200).json({ success: true, data: org });
  } catch (error) {
    return errorResponse(res, "Failed to update organization", 400, error);
  }
};

// Soft Delete Organization
const deleteOrg = async (req, res) => {
  try {
    const userId = req.user?._id;

    const org = await Organization.findByIdAndUpdate(
      req.params.id,
      { isDeleted: true, updatedBy: userId || null },
      { new: true }
    );

    if (!org) return errorResponse(res, "Organization not found", 404);

    // Log user action
    await logUserAction({
      userId,
      orgId: org._id,
      action: "DELETE",
      model: "Organization",
      details: { orgId: org._id },
      req,
    });

    res.status(200).json({
      success: true,
      message: "Organization deleted successfully",
      data: org,
    });
  } catch (error) {
    return errorResponse(res, "Failed to delete organization", 500, error);
  }
};

module.exports = {
  createOrg,
  getOrgs,
  getOrgById,
  updateOrg,
  deleteOrg,
};
