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

const servicesModel = sequelize.define("services", {
  service_label: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  content_heading: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  service_content: {
    type: DataTypes.TEXT,
    allowNull: false,
  },
  service_img: {
    type: DataTypes.STRING,
    allowNull: true,
  },
  img_alt: {
    type: DataTypes.STRING,
    allowNull: true,
  },
  is_active: {
    type: DataTypes.BOOLEAN,
    defaultValue: true,
  },
  show_on_home: {
    type: DataTypes.BOOLEAN,
    defaultValue: false,
  },
  is_featured: {
    type: DataTypes.BOOLEAN,
    defaultValue: false,
  },
}, {
  tableName: "services",
  underscored: true,
});

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

const services = {
  create: async (data) => {
    try {
      if (!data.service_label || !data.content_heading || !data.service_content) {
        return { error: "Required fields missing." };
      }
      return await servicesModel.create(data);
    } catch (err) {
      throw err;
    }
  },

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

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

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

      // Delete old image if new uploaded
      if (data.service_img && existing.service_img) {
        const oldPath = path.join(process.cwd(), existing.service_img.replace(/^\//, ""));
        if (fs.existsSync(oldPath)) fs.unlinkSync(oldPath);
      }

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

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

      const deleted = await servicesModel.destroy({ where: { id } });
      if (!deleted) return null;
      return { message: "Service deleted successfully!" };
    } catch (err) {
      throw err;
    }
  },
};

module.exports = { servicesModel, services };
