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

exports.getAllColleges = async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const offset = (page - 1) * limit;

    const { count, rows: colleges } = await db.MainCollege.findAndCountAll({
      attributes: [
        "college_id",
        "college_name",
        "college_city_name",
        "college_state_name",
        "logo_image_url",
        "estd_year",
        "is_featured",
        "college_website",
        "college_desc",
        "college_contact",
        "college_email",
      ],
      include: [
        {
          model: db.CollegeReview,
          as: "reviews",
          attributes: ["rating"],
          required: false,
        },
        {
          model: db.CollegeImage,
          as: "images",
          attributes: ["image_url", "is_logo"],
          required: false,
        },
        {
          model: db.CollegeComparison,
          as: "comparisonData", // Changed to match model association
          attributes: ["highest_package", "average_package", "ratings"],
          required: false,
        },
      ],
      order: [["college_name", "ASC"]],
      limit,
      offset,
    });

    const response = {
      success: true,
      pagination: {
        total: count,
        pages: Math.ceil(count / limit),
        currentPage: page,
        perPage: limit,
      },
      data: colleges.map((college) => {
        const avgRating =
          college.reviews?.length > 0
            ? college.reviews.reduce((sum, review) => sum + review.rating, 0) /
              college.reviews.length
            : 0;

        const bannerImages = college.images
          ? college.images
              .filter((img) => !img.is_logo)
              .map((img) => img.image_url)
          : [];

        return {
          id: college.college_id,
          name: college.college_name,
          city: college.college_city_name,
          state: college.college_state_name,
          logo: college.logo_image_url,
          established: college.estd_year,
          isFeatured: college.is_featured === 1,
          website: college.college_website,
          description: college.college_desc,
          contact: college.college_contact,
          email: college.college_email,
          packages: {
            highest: college.comparisonData?.highest_package,
            average: college.comparisonData?.average_package,
          },
          rating: parseFloat(avgRating.toFixed(1)),
          comparisonRating: college.comparisonData?.ratings || 0, // Added comparison rating
          reviewCount: college.reviews?.length || 0,
          media: {
            images: bannerImages,
            logo:
              college.images?.find((img) => img.is_logo)?.image_url ||
              college.logo_image_url,
          },
        };
      }),
    };

    res.json(response);
  } catch (error) {
    console.error("Error fetching college data:", error);
    res.status(500).json({
      success: false,
      message: "Failed to fetch college data",
      error: error.message,
    });
  }
};

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

    const college = await db.MainCollege.findByPk(id, {
      include: [
        { model: db.CollegeComparison, as: "comparisonData" }, // Changed to match model
        { model: db.CollegeCourse, as: "courses" },
        { model: db.CollegeImage, as: "images" },
        { model: db.CollegeReview, as: "reviews" },
        { model: db.CollegeVideo, as: "videos" },
      ],
      attributes: {
        exclude: ["password", "username", "is_checkout"],
      },
    });

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

    // Calculate average rating
    const avgRating =
      college.reviews.length > 0
        ? college.reviews.reduce((sum, review) => sum + review.rating, 0) /
          college.reviews.length
        : 0;

    // Prepare response
    const response = {
      success: true,
      data: {
        basicInfo: {
          id: college.college_id,
          name: college.college_name,
          city: college.college_city_name,
          state: college.college_state_name,
          established: college.estd_year,
          logo: college.logo_image_url,
          description: college.college_desc,
          facilities: college.college_facilities,
          website: college.college_website,
          contact: college.college_contact,
          email: college.college_email,
          address: college.college_address,
          isFeatured: college.is_featured === 1,
          meta: {
            title: college.collage_page_title,
            description: college.collage_meta_desc,
            keywords: college.collage_meta_char,
          },
        },
        comparisonData: college.comparisonData
          ? {
              placements: college.comparisonData.placements,
              packages: {
                highest: college.comparisonData.highest_package,
                average: college.comparisonData.average_package,
                lowest: college.comparisonData.lowest_package,
              },
              accreditation: college.comparisonData.accreditation,
              affiliation: college.comparisonData.affiliation,
              infrastructure: college.comparisonData.infrascructure,
              ratings: college.comparisonData.ratings,
            }
          : null,
        courses: college.courses.map((course) => ({
          id: course.course_id,
          name: course.course_name,
          fees: course.course_fees,
          duration: course.course_duration,
          mode: course.course_mode,
          approval: course.degree_approval,
        })),
        media: {
          images: college.images
            .filter((img) => !img.is_logo)
            .map((img) => img.image_url),
          logo:
            college.images.find((img) => img.is_logo)?.image_url ||
            college.logo_image_url,
          videos: college.videos.map((video) => video.video_url),
        },
        reviews: {
          averageRating: avgRating.toFixed(1),
          totalReviews: college.reviews.length,
          reviews: college.reviews.map((review) => ({
            id: review.review_id,
            reviewer: review.reviewer_name,
            rating: review.rating,
            comment: review.review_text,
          })),
        },
      },
    };

    res.json(response);
  } catch (error) {
    console.error("Error fetching college data:", error);
    res.status(500).json({
      success: false,
      message: "Failed to fetch college data",
      error: error.message,
    });
  }
};
