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

// Add this middleware before your routes

exports.createLandingPage = async (req, res) => {
  try {
    // Debug received data
    // console.log("Request body:", req.body);
    // console.log("Request files:", req.files);

    // Validate required fields
    if (!req.body.collegeURL || req.body.collegeURL.trim() === "") {
      console.log("Validation failed - collegeURL:", req.body.collegeURL);
      return res.status(400).json({ error: "College URL is required" });
    }

    // Check for existing landing page
    const existingLanding = await db.Landingpage.findOne({
      where: { college_url: req.body.collegeURL },
    });

    if (existingLanding) {
      return res.status(400).json({ error: "Landing Page already exists" });
    }

    // Prepare data for database
    const dbData = {
      college_name: req.body.collegeName,
      college_url: req.body.collegeURL,
      college_banner: req.files?.collegeBanner?.data || null,
      college_logo: req.files?.collegeLogo?.data || null,
      title_1: req.body.title1Description,
      description_1: req.body.title2Description,
      title_2: JSON.parse(req.body.recordingCategories).join(", "), // Convert array to string
      description_2: req.body.collegeDescription1,
      companies: req.body.collegeDescription2,
    };

    // Create new landing page
    const landingPage = await db.Landingpage.create(dbData);

    return res.status(201).json({
      success: true,
      message: "LandingPage created successfully",
      data: landingPage,
    });
  } catch (err) {
    console.error("Error creating landing page:", err);
    return res.status(500).json({
      success: false,
      error: "Failed to create landing page",
      details: process.env.NODE_ENV === "development" ? err.message : undefined,
    });
  }
};

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

    // If college_url is provided, fetch by college_url
    if (college_url) {
      const landingPage = await db.Landingpage.findOne({
        where: { college_url },
      });

      if (!landingPage) {
        return res.status(404).json({ error: "Landing page not found" });
      }

      return res.json(landingPage);
    }

    // If no query, return all landing pages
    const landingpages = await db.Landingpage.findAll();
    res.json(landingpages);
    
  } catch (err) {
    console.error("Error fetching landing pages:", err);
    res.status(500).json({ error: "Failed to fetch landing pages" });
  }
};

