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

const services_detail_media = sequelize.define("services_detail_media", {
  file_url: {
    type: DataTypes.STRING,
    allowNull: false,
  },
}, {
  tableName: "services_detail_media",
  underscored: true,
});

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

const services_detail_mediaModel = {
  create: async (data) => {
    if (!data.file_url) return { error: " file is required." };
    return await services_detail_media.create(data);
  },

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

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

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

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

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

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

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

module.exports = { services_detail_media, services_detail_mediaModel };
