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

const section4VideoModel = sequelize.define("section_4_video", {
  video_url: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  video_alt: {
    type: DataTypes.STRING,
    allowNull: true,
  },
}, {
  tableName: "section_4_video",
  underscored: true,
});

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

const section4Video = {
  create: async (data) => {
    if (!data.video_url) return { error: "Video file is required." };
    return await section4VideoModel.create(data);
  },

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

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

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

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

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

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

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

module.exports = { section4VideoModel, section4Video };
