const Institution = require("../models/institutionModel");
const Setting = require("../models/settingModel");
const fs = require("fs");
const path = require("path");

// =======================================================
// == CONTROLLERS FOR SUPER ADMINS                      ==
// =======================================================

/**
 * @desc    Create a new institution (file upload not handled here, done in update)
 */
exports.createInstitution = async (req, res) => {
  try {
    const { name, contact_email, contact_phone, address } = req.body;
    if (!name || !contact_email) {
      return res
        .status(400)
        .json({ message: "Institution name and contact email are required." });
    }
    // Logo is not handled on creation, it's added via an update after the institution exists.
    const newInstitution = await Institution.create({
      name,
      contact_email,
      contact_phone,
      address,
    });
    res.status(201).json({
      message: "Institution created successfully. You can now upload a logo.",
      institution: newInstitution,
    });
  } catch (error) {
    if (error.code === "ER_DUP_ENTRY") {
      return res.status(409).json({
        message: "An institution with this contact email already exists.",
      });
    }
    res.status(500).json({
      message: "Server error creating institution",
      error: error.message,
    });
  }
};

/**
 * @desc    Get all institutions
 */
exports.getAllInstitutions = async (req, res) => {
  try {
    const institutions = await Institution.findAll();
    res.status(200).json(institutions);
  } catch (error) {
    res.status(500).json({
      message: "Server error fetching institutions",
      error: error.message,
    });
  }
};

/**
 * @desc    Get a single institution by ID
 */
exports.getInstitutionById = async (req, res) => {
  try {
    const institution = await Institution.findById(req.params.id);
    if (!institution) {
      return res.status(404).json({ message: "Institution not found." });
    }
    res.status(200).json(institution);
  } catch (error) {
    res.status(500).json({
      message: "Server error fetching institution",
      error: error.message,
    });
  }
};

/**
 * @desc    Update an institution's details, including logo upload
 * @route   PUT /api/institutions/:id
 */
exports.updateInstitution = async (req, res) => {
  try {
    const updateData = { ...req.body };

    // If a file was uploaded by multer, construct its public URL
    if (req.file) {
      // Example: http://localhost:5000/assets/logo-1-1678886400000.png
      const logoUrl = `${req.protocol}://${req.get("host")}/assets/${
        req.file.filename
      }`;
      updateData.logo_url = logoUrl;
    }

    const success = await Institution.update(req.params.id, updateData);
    if (success) {
      res.status(200).json({ message: "Institution updated successfully." });
    } else {
      res
        .status(404)
        .json({ message: "Institution not found or no changes made." });
    }
  } catch (error) {
    res.status(500).json({
      message: "Server error updating institution",
      error: error.message,
    });
  }
};

/**
 * @desc    Update an institution's status
 */
exports.updateInstitutionStatus = async (req, res) => {
  // ... no changes here ...
  try {
    const { status } = req.body;
    if (!["active", "inactive", "suspended"].includes(status)) {
      return res.status(400).json({ message: "Invalid status provided." });
    }
    const success = await Institution.setStatus(req.params.id, status);
    if (success) {
      res
        .status(200)
        .json({ message: `Institution status updated to ${status}.` });
    } else {
      res.status(404).json({ message: "Institution not found." });
    }
  } catch (error) {
    res
      .status(500)
      .json({ message: "Server error updating status", error: error.message });
  }
};

// =======================================================
// == CONTROLLER FOR INSTITUTION ADMINS                 ==
// =======================================================

/**
 * @desc    Get details of the currently logged-in user's institution
 */
exports.getMyInstitution = async (req, res) => {
  try {
    const { institution_id } = req.user;
    if (!institution_id) {
      return res
        .status(400)
        .json({ message: "This user is not associated with an institution." });
    }
    // The findById model function now joins with settings, providing all needed data
    const institution = await Institution.findById(institution_id);
    if (!institution) {
      return res
        .status(404)
        .json({ message: "Associated institution not found." });
    }
    res.status(200).json(institution);
  } catch (error) {
    res.status(500).json({
      message: "Server error fetching institution details",
      error: error.message,
    });
  }
};


exports.updateMyInstitutionLogo = async (req, res) => {
  try {
    const { institution_id } = req.user;

    // Check if a file was actually uploaded
    if (!req.file) {
      return res.status(400).json({ message: "No logo file was uploaded." });
    }

    // 1. Find the old logo to delete it
    const currentDetails = await Institution.findById(institution_id);
    if (currentDetails && currentDetails.logo_url) {
      const oldLogoPath = path.join(__dirname, "..", currentDetails.logo_url);
      if (fs.existsSync(oldLogoPath)) {
        fs.unlink(oldLogoPath, (err) => {
          if (err) console.error("Failed to delete old logo:", err.message);
          else console.log("Successfully deleted old logo:", oldLogoPath);
        });
      }
    }

    // 2. Prepare the new logo URL
    const newLogoUrl = `/assets/logos/${req.file.filename}`;

    // 3. Update only the logo_url in the database
    await Institution.updateById(institution_id, { logo_url: newLogoUrl });

    // 4. Return success and the new URL for immediate UI update
    res.status(200).json({
      message: "Logo updated successfully.",
      logo_url: newLogoUrl,
    });
  } catch (error) {
    console.error("ERROR in updateMyInstitutionLogo:", error);
    res
      .status(500)
      .json({ message: "Error updating logo.", error: error.message });
  }
};

/**
 * @desc    (SIMPLIFIED) Update TEXT details for the logged-in user's institution
 * @route   PUT /api/institutions/my-institution/details
 * @access  Private (Admin)
 */
exports.updateMyInstitutionDetails = async (req, res) => {
  try {
    const { institution_id } = req.user;

    // This controller now only handles JSON data. No more file logic!
    const { name, contact_email, contact_phone, address } = req.body;
    const { sms_base_url, sms_sender_id, sms_api_key } = req.body;

    const institutionData = { name, contact_email, contact_phone, address };
    const settingsData = { sms_base_url, sms_sender_id, sms_api_key };

    await Promise.all([
      Institution.updateById(institution_id, institutionData),
      Setting.createOrUpdate(institution_id, settingsData),
    ]);

    res
      .status(200)
      .json({ message: "Institution details updated successfully." });
  } catch (error) {
    console.error("ERROR in updateMyInstitutionDetails:", error);
    res
      .status(500)
      .json({ message: "Error updating details.", error: error.message });
  }
};
