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

const pageBlogModel = sequelize.define("page_blog", {
  main_heading: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  content: {
    type: DataTypes.TEXT,
    allowNull: false,
  },
  blog_image: {
    type: DataTypes.STRING,
    allowNull: true,
  },
}, {
  tableName: "page_blog",
  underscored: true,
});

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

const pageBlog = {
  create: async (data) => {
    try {
      if (!data.main_heading) return { error: "Main heading is required." };
      if (!data.content) return { error: "Content is required." };
      const newEntry = await pageBlogModel.create(data);
      return newEntry;
    } catch (err) {
      throw err;
    }
  },

  getAll: async () => {
    try {
      const entries = await pageBlogModel.findAll({ order: [["created_at", "DESC"]] });
      const baseUrl = process.env.BASE_URL || "http://localhost:3000";

      return entries.map((entry) => {
        const data = entry.toJSON();
        if (data.blog_image && !data.blog_image.startsWith("http")) {
          data.blog_image = baseUrl.replace(/\/$/, "") + data.blog_image;
        }
        return data;
      });
    } catch (err) {
      throw err;
    }
  },

  getSingle: async (id) => {
    try {
      const entry = await pageBlogModel.findByPk(id);
      if (!entry) return null;
      const data = entry.toJSON();
      const baseUrl = process.env.BASE_URL || "http://localhost:3000";

      if (data.blog_image && !data.blog_image.startsWith("http")) {
        data.blog_image = baseUrl.replace(/\/$/, "") + data.blog_image;
      }

      return data;
    } catch (err) {
      throw err;
    }
  },

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

      // Delete old image if new one provided
      if (data.blog_image && record.blog_image) {
        const oldPath = path.join(
          process.cwd(),
          record.blog_image.startsWith("/") ? record.blog_image.slice(1) : record.blog_image
        );
        if (fs.existsSync(oldPath)) fs.unlinkSync(oldPath);
      }

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

  delete: async (id) => {
    try {
      const deleted = await pageBlogModel.destroy({ where: { id } });
      if (!deleted) return null;
      return { message: "Page blog deleted successfully!" };
    } catch (err) {
      throw err;
    }
  },
};

module.exports = { pageBlogModel, pageBlog };
