const { DataTypes } = require("sequelize");
const sequelize = require("../../config/sequelize");

const sliderBannerModel = sequelize.define("slider_banner", {
  main_heading: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  content: {
    type: DataTypes.TEXT,
    allowNull: false,
  },
  button_text: {
    type: DataTypes.STRING,
    allowNull: true,
  },
  button_link: {
    type: DataTypes.STRING,
    allowNull: true,
  },
  banner_img: {
    type: DataTypes.STRING,
    allowNull: true,
  },
  img_alt: {
    type: DataTypes.STRING,
    allowNull: true,
  },
}, {
  tableName: "slider_banner",
  underscored: true,
});

const fs = require("fs");
const path = require("path");

const sliderBanner = {
  create: async (data) => {
    try {
      if (!data.main_heading || !data.content) return { error: "Main heading and content are required." };
      return await sliderBannerModel.create(data);
    } catch (err) {
      throw err;
    }
  },

  getAll: async () => {
    try {
      const entries = await sliderBannerModel.findAll({ order: [["created_at", "DESC"]] });
      const baseUrl = process.env.BASE_URL || "http://localhost:3000";
      return entries.map((entry) => {
        const data = entry.toJSON();
        if (data.banner_img && !data.banner_img.startsWith("http")) {
          data.banner_img = baseUrl.replace(/\/$/, "") + data.banner_img;
        }
        return data;
      });
    } catch (err) {
      throw err;
    }
  },

  getSingle: async (id) => {
    try {
      const entry = await sliderBannerModel.findByPk(id);
      if (!entry) return null;
      const data = entry.toJSON();
      const baseUrl = process.env.BASE_URL || "http://localhost:3000";
      if (data.banner_img && !data.banner_img.startsWith("http")) {
        data.banner_img = baseUrl.replace(/\/$/, "") + data.banner_img;
      }
      return data;
    } catch (err) {
      throw err;
    }
  },

  update: async (id, data) => {
    try {
      const record = await sliderBannerModel.findByPk(id);
      if (!record) return null;

      if (data.banner_img && record.banner_img) {
        const oldPath = path.join(process.cwd(), record.banner_img.replace(/^\//, ""));
        if (fs.existsSync(oldPath)) fs.unlinkSync(oldPath);
      }

      await sliderBannerModel.update(data, { where: { id } });
      return await sliderBannerModel.findByPk(id);
    } catch (err) {
      throw err;
    }
  },

  delete: async (id) => {
    try {
      const record = await sliderBannerModel.findByPk(id);
      if (record?.banner_img) {
        const imgPath = path.join(process.cwd(), record.banner_img.replace(/^\//, ""));
        if (fs.existsSync(imgPath)) fs.unlinkSync(imgPath);
      }
      const deleted = await sliderBannerModel.destroy({ where: { id } });
      if (!deleted) return null;
      return { message: "Slider banner deleted successfully!" };
    } catch (err) {
      throw err;
    }
  },
};

module.exports = { sliderBannerModel, sliderBanner };
