const db = require("../../db");
const bcrypt = require("bcrypt");

exports.createCollege = async (req, res) => {
  try {
    const requiredFields = [
      "collegeName",
      "group",
      "country",
      "userName",
      "password",
    ];
    const missingFields = requiredFields.filter((field) => !req.body[field]);

    if (missingFields.length > 0) {
      return res.status(400).json({
        error: "Missing required fields",
        missingFields,
      });
    }

    const existingCollege = await db.College.findOne({
      where: { college_name: req.body.collegeName },
    });

    if (existingCollege) {
      return res.status(400).json({ error: "College already exists" });
    }

    const hashedPassword = await bcrypt.hash(req.body.password, 10);

    const dbData = {
      college_name: req.body.collegeName || "",
      fk_group_id: parseInt(req.body.group) || 0,
      fk_country_id: parseInt(req.body.country) || 0,
      username: req.body.userName || "",
      password: hashedPassword,
      display_name: req.body.displayName || "",
      college_usp: req.body.collegeUSP || "",
      college_desc: req.body.collegeDescription || "",
      college_address: req.body.collegeAddress || "",
      form_open_date: req.body.admissionOpeningDate || new Date(),
      form_close_date: req.body.admissionClosingDate || new Date(),
      college_email: req.body.email || "",
      college_contact: req.body.contactNumber || "",
      estd_year: req.body.yearOfEstablishment || "",
      organization_type: req.body.orgType || "",
      college_website: req.body.websiteURL || "",
      collage_page_title: req.body.pageTitle || "",
      college_url: req.body.bmcCollegeURL || "",
      alt_tag: req.body.imageAltTag || "",
      collage_meta_char: req.body.pageMetaChar || "",
      collage_meta_desc: req.body.pageMetaDescription || "",
      other_name: "",
      other_name1: "",
      city_name: "",
      placement: "",
      college_city_name: "",
      college_state_name: "",
      contact_person: "",
      college_facilities: "",
      logo_image_url: "",
      is_featured: 0,
      is_silver: 0,
      is_gold: 0,
      is_platinum: 0,
      is_published: 0,
      is_approved: 0,
      is_checkout: 0,
      fk_city_id: 0,
      fk_indiacity_id: 0,
      fk_state_id: 0,
      cover_image_id: 0,
    };

    const college = await db.College.create(dbData);

    res.status(201).json({
      success: true,
      message: "College created successfully",
      collegeId: college.college_id,
    });
  } catch (err) {
    console.error("Error:", err);
    res.status(500).json({
      success: false,
      error: "Failed to create college",
      details:
        process.env.NODE_ENV === "development"
          ? { message: err.message, stack: err.stack }
          : undefined,
    });
  }
};

exports.getCollege = async (req, res) => {
  try {
    const colleges = await db.College.findAll({
      include: [
        {
          model: db.CollegeComparison,
          as: "comparisonData",
          attributes: [
            "fees_course",
            "highest_package",
            "average_package",
            "ratings",
            "ranking",
          ],
        },
        {
          model: db.CollegeCourse,
          as: "courses",
          attributes: ["course_name", "course_fees", "course_duration"],
          limit: 3,
        },
      ],
      attributes: [
        "college_id",
        "college_name",
        "city_name",
        "college_state_name",
        "logo_image_url",
        "placement",
      ],
      order: [["college_name", "ASC"]],
    });

    const transformedColleges = colleges.map((college) => {
      const plainCollege = college.get({ plain: true });
      return {
        ...plainCollege,
        course_fees:
          plainCollege.comparisonData?.fees_course || "Not available",
        highest_package:
          plainCollege.comparisonData?.highest_package || "Not available",
        average_package:
          plainCollege.comparisonData?.average_package || "Not available",
        user_reviews: plainCollege.comparisonData?.ratings
          ? `${plainCollege.comparisonData.ratings}/5`
          : "Not rated",
        ranking: plainCollege.comparisonData?.ranking || "Not ranked",
        placement:
          plainCollege.placement ||
          (plainCollege.comparisonData?.placements
            ? `${plainCollege.comparisonData.placements}%`
            : "Not available"),
        top_courses:
          plainCollege.courses?.map((course) => ({
            name: course.course_name,
            fees: course.course_fees
              ? `₹${course.course_fees.toLocaleString("en-IN")}`
              : "Not available",
            duration: course.course_duration || "Not specified",
          })) || [],
      };
    });

    res.json({
      success: true,
      data: transformedColleges,
      count: transformedColleges.length,
    });
  } catch (err) {
    console.error("Error fetching colleges:", err);
    res.status(500).json({
      success: false,
      error: "Failed to fetch colleges",
      details: process.env.NODE_ENV === "development" ? err.message : undefined,
    });
  }
};

exports.deleteCollege = async (req, res) => {
  try {
    const collegeId = req.params.id;

    if (!collegeId) {
      return res.status(400).json({
        status: false,
        message: "College id is required",
      });
    }

    const college = await db.College.findByPk(collegeId);
    if (!college) {
      return res.status(404).json({
        status: false,
        message: "College not found",
      });
    }

    await college.destroy();

    res.status(200).json({
      status: true,
      message: "College deleted successfully",
    });
  } catch (error) {
    console.error("Delete error:", error);
    res.status(500).json({
      status: false,
      message: "Failed to delete college",
      error: error.message,
    });
  }
};

exports.getMultipleCollegeDetails = async (req, res) => {
  try {
    const { ids } = req.query;

    if (!ids) {
      return res.status(400).json({
        success: false,
        error: "College IDs are required as comma-separated values",
      });
    }

    const collegeIds = ids.split(",").map((id) => parseInt(id.trim()));

    const colleges = await db.College.findAll({
      where: {
        college_id: collegeIds,
      },
      include: [
        {
          model: db.CollegeComparison,
          as: "comparisonData",
          attributes: [
            "fees_course",
            "placements",
            "highest_package",
            "average_package",
            "ratings",
            "ranking",
          ],
        },
      ],
      attributes: ["college_id", "college_name", "placement", "logo_image_url"],
    });

    if (!colleges.length) {
      return res.status(404).json({
        success: false,
        error: "No colleges found",
      });
    }

    // Format the response data
    const responseData = colleges.map((college) => ({
      college_id: college.college_id,
      college_name: college.college_name,
      logo_url: college.logo_image_url,
      placement: college.placement,
      course_fees: college.comparisonData?.fees_course || "Not available",
      highest_package:
        college.comparisonData?.highest_package || "Not available",
      average_package:
        college.comparisonData?.average_package || "Not available",
      user_reviews: college.comparisonData?.ratings
        ? `${college.comparisonData.ratings}/5`
        : "Not rated",
      ranking: college.comparisonData?.ranking || "Not ranked",
    }));

    res.json({
      success: true,
      data: responseData,
    });
  } catch (err) {
    console.error("Error fetching college details:", err);
    res.status(500).json({
      success: false,
      error: "Failed to fetch college details",
      details: process.env.NODE_ENV === "development" ? err.message : undefined,
    });
  }
};

// Add this to your collegeController.js
exports.getCollegeDetails = async (req, res) => {
  try {
    const { id } = req.params;

    if (!id) {
      return res.status(400).json({
        success: false,
        error: "College ID is required",
      });
    }

    const college = await db.College.findByPk(id, {
      include: [
        {
          model: db.CollegeComparison,
          as: "comparisonData",
          attributes: [
            "fees_course",
            "placements",
            "highest_package",
            "average_package",
            "ratings",
            "ranking",
          ],
        },
      ],
      attributes: ["college_id", "college_name", "placement", "logo_image_url"],
    });

    if (!college) {
      return res.status(404).json({
        success: false,
        error: "College not found",
      });
    }

    // Format the response data
    const responseData = {
      college_id: college.college_id,
      college_name: college.college_name,
      logo_url: college.logo_image_url,
      placement: college.placement,
      course_fees: college.comparisonData?.fees_course || "Not available",
      highest_package:
        college.comparisonData?.highest_package || "Not available",
      average_package:
        college.comparisonData?.average_package || "Not available",
      user_reviews: college.comparisonData?.ratings
        ? `${college.comparisonData.ratings}/5`
        : "Not rated",
      ranking: college.comparisonData?.ranking || "Not ranked",
    };

    res.json({
      success: true,
      data: responseData,
    });
  } catch (err) {
    console.error("Error fetching college details:", err);
    res.status(500).json({
      success: false,
      error: "Failed to fetch college details",
      details: process.env.NODE_ENV === "development" ? err.message : undefined,
    });
  }
};
