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

const logosliderModel = sequelize.define("logo", {
  image_path: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  img_alt: {
    type: DataTypes.STRING,
    allowNull: true,
  },
  logo_for: {
    type: DataTypes.ENUM("Award_logo", "Partners_logo"),
    allowNull: false,
  },
}, {
  tableName: "logos_slider",
  underscored: true,
});

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

const logoslider = {
  create: async (data) => {
    if (!data.image_path || !data.logo_for) return { error: "Image and logo_for are required." };
    return await logosliderModel.create(data);
  },

  getAll: async () => {
    const baseUrl = process.env.BASE_URL || "http://localhost:3000";
    const logos = await logosliderModel.findAll({ order: [["created_at", "DESC"]] });
    return logos.map(item => {
      const data = item.toJSON();
      if (data.image_path && !data.image_path.startsWith("http")) {
        data.image_path = baseUrl.replace(/\/$/, "") + data.image_path;
      }
      return data;
    });
  },


  filterlogoforwise: async (logo_for) => {
    const baseUrl = process.env.BASE_URL || "http://localhost:3000";
    const logos = await logosliderModel.findAll({
      where: { logo_for },
      order: [["created_at", "DESC"]],
    });
    return logos.map(item => {
      const data = item.toJSON();
      if (data.image_path && !data.image_path.startsWith("http")) {
        data.image_path = baseUrl.replace(/\/$/, "") + data.image_path;
      }
      return data;
    }

    );
  },
  

  getSingle: async (id) => {
    const entry = await logosliderModel.findByPk(id);
    if (!entry) return null;

    const data = entry.toJSON();
    const baseUrl = process.env.BASE_URL || "http://localhost:3000";
    if (data.image_path && !data.image_path.startsWith("http")) {
      data.image_path = baseUrl.replace(/\/$/, "") + data.image_path;
    }
    return data;
  },

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

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

    await logosliderModel.update(data, { where: { id } });
    return await logosliderModel.findByPk(id);
  },

  delete: async (id) => {
    const existing = await logosliderModel.findByPk(id);
    if (existing?.image_path) {
      const filePath = path.join(process.cwd(), existing.image_path.replace(/^\//, ""));
      if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
    }

    const deleted = await logosliderModel.destroy({ where: { id } });
    if (!deleted) return null;
    return { message: "Logo deleted successfully!" };
  },
};

module.exports = { logosliderModel, logoslider };
