// controllers/collegeCourseController.js
const db = require("../db");

// Course mapping matching your ACTUAL database entries
const COURSE_MAPPING = {
  engineering: [
    "8.Tech", // Note the '8' which appears in your database
    "8.Tech Computer Science",
    "8.Tech in Electronics",
    "Bachelor of Technology (8.Tech)",
    "Engineering", // More generic term as fallback
  ],
  management: ["MBA", "PGDM"],
  medical: ["MBBS"],
  law: ["LLB"],
  commerce: ["B.Com"],
  science: ["B.Sc"],
  arts: ["BA"],
};

exports.getCollegesByCourse = async (req, res) => {
  try {
    const { courseKey } = req.params;

    if (!COURSE_MAPPING[courseKey]) {
      return res.status(400).json({
        success: false,
        error: "Invalid course key",
        validKeys: Object.keys(COURSE_MAPPING),
        databaseCheck:
          "Try these exact names: '8.Tech', '8.Tech Computer Science'",
      });
    }

    const searchTerms = COURSE_MAPPING[courseKey];

    // First try exact matches
    let courses = await db.CollegeCourse.findAll({
      where: {
        [db.Sequelize.Op.or]: searchTerms.map((term) => ({
          course_name: {
            [db.Sequelize.Op.like]: `%${term}%`,
          },
        })),
      },
      include: [
        {
          model: db.College,
          as: "college",
          required: true,
          attributes: [
            "college_id",
            "college_name",
            "city_name",
            "logo_image_url",
          ],
        },
      ],
      logging: console.log,
    });

    if (!courses || courses.length === 0) {
      return res.status(404).json({
        success: false,
        error: "No matching courses found",
        searchedTerms: searchTerms,
        databaseQueryExample:
          "SELECT * FROM tbl_college_courses WHERE course_name LIKE '%8.Tech%' LIMIT 5;",
        solution: "Verify course names in database match the search terms",
      });
    }

    const results = courses.map((course) => ({
      college_id: course.college.college_id,
      college_name: course.college.college_name,
      city: course.college.city_name,
      logo: course.college.logo_image_url,
      course_id: course.course_id,
      course_name: course.course_name,
      fees: course.course_fees,
      duration: course.course_duration,
      mode: course.course_mode,
    }));

    res.json({
      success: true,
      count: results.length,
      data: results,
      matchedTerms: searchTerms.filter((term) =>
        courses.some((c) => c.course_name.includes(term))
      ),
    });
  } catch (err) {
    console.error("Server Error:", err);
    res.status(500).json({
      success: false,
      error: "Internal server error",
      detailedError:
        process.env.NODE_ENV === "development"
          ? {
              message: err.message,
              stack: err.stack,
              sql: err.sql, // Sequelize errors include SQL
            }
          : undefined,
    });
  }
};
