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

exports.getAllBanners = async (req, res) => {
  try {
    const banners = await db.Banner.findAll({
      attributes: ["id", "college_name", "link", "userfile"],
    });
    res.json({ success: true, data: banners });
  } catch (err) {
    console.error(err);
    res
      .status(500)
      .json({ success: false, message: "Failed to fetch banners" });
  }
};

exports.createBanner = async (req, res) => {
  try {
    const { college_name, link } = req.body;
    const imageName = req.file ? req.file.filename : null;

    const newBanner = await db.Banner.create({
      college_name,
      link: link || "link",
      userfile: imageName,
    });

    res.status(201).json({
      success: true,
      data: {
        id: newBanner.id,
        college_name: newBanner.college_name,
        userfile: newBanner.userfile,
        link: newBanner.link,
      },
    });
  } catch (err) {
    console.error(err);
    res
      .status(500)
      .json({ success: false, message: "Failed to create banner" });
  }
};

exports.updateBanner = async (req, res) => {
  try {
    const banner = await db.Banner.findByPk(req.params.id);
    if (!banner) {
      return res
        .status(404)
        .json({ success: false, message: "Banner not found" });
    }

    const updateData = {
      college_name: req.body.college_name || banner.college_name,
      link: req.body.link || banner.link,
    };

    if (req.file) {
      updateData.userfile = req.file.filename;
    }

    await banner.update(updateData);

    res.json({
      success: true,
      data: {
        id: banner.id,
        college_name: banner.college_name,
        userfile: banner.userfile,
        link: banner.link,
      },
    });
  } catch (err) {
    console.error(err);
    res
      .status(500)
      .json({ success: false, message: "Failed to update banner" });
  }
};

exports.deleteBanner = async (req, res) => {
  try {
    const deleted = await db.Banner.destroy({ where: { id: req.params.id } });
    if (!deleted) {
      return res
        .status(404)
        .json({ success: false, message: "Banner not found" });
    }
    res.json({ success: true, message: "Banner deleted successfully" });
  } catch (err) {
    console.error(err);
    res
      .status(500)
      .json({ success: false, message: "Failed to delete banner" });
  }
};
