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

const whoWeAreModel = sequelize.define("who_we_are", {
  span_heading: {
    type: DataTypes.STRING,
    allowNull: true,
  },
  main_heading_1: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  main_heading_2: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  main_heading_img: {
    type: DataTypes.STRING,
    allowNull: true,
  },
  content: {
    type: DataTypes.TEXT,
    allowNull: false,
  },
  button_text: {
    type: DataTypes.STRING,
    allowNull: true,
  },
  button_link: {
    type: DataTypes.STRING,
    allowNull: true,
  },
}, {
  tableName: "who_we_are",
  underscored: true,
});

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

const whoWeAre = {
  create: async (data) => {
    if (!data.main_heading_1 || !data.main_heading_2 || !data.content) {
      return { error: "Main headings and content are required." };
    }
    return await whoWeAreModel.create(data);
  },

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

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

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

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

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

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

    const deleted = await whoWeAreModel.destroy({ where: { id } });
    if (!deleted) return null;
    return { message: "Who We Are section deleted successfully!" };
  },
};

module.exports = { whoWeAreModel, whoWeAre };
