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

const iconBoxModel = sequelize.define("icon_box", {
  card_title: { type: DataTypes.STRING, allowNull: false },
  card_content: { type: DataTypes.STRING, allowNull: false },
  image_path: { type: DataTypes.STRING, allowNull: true },
  img_alt: { type: DataTypes.STRING, allowNull: true },
}, {
  tableName: "icon_boxes",
  underscored: true,
});

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

const iconBox = {
  create: async (data) => {
    if (!data.card_title || !data.card_content) {
      return { error: "Card title and content are required." };
    }
    return await iconBoxModel.create(data);
  },

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

  getSingle: async (id) => {
    const record = await iconBoxModel.findByPk(id);
    if (!record) return null;
    const data = record.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 record = await iconBoxModel.findByPk(id);
    if (!record) return null;

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

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

  delete: async (id) => {
    const record = await iconBoxModel.findByPk(id);
    if (record?.image_path) {
      const imgPath = path.join(process.cwd(), record.image_path.replace(/^\//, ""));
      if (fs.existsSync(imgPath)) fs.unlinkSync(imgPath);
    }
    const deleted = await iconBoxModel.destroy({ where: { id } });
    if (!deleted) return null;
    return { message: "Icon box deleted successfully!" };
  },
};

module.exports = { iconBoxModel, iconBox };
