const TblArtigo = require("../models/TblArtigos");
const path = require('path');
const os = require('os');
const dotenv = require("dotenv").config();
const fs = require('fs').promises; // Using the promises version for asynchronous file operations





const getAllArtigos = async (queryParams = {}) => {
  return TblArtigo.findAll({
    where: queryParams,
  });
};

const getArtigoById = async (id, queryParams = {}) => {
  const whereCondition = { intId: id, ...queryParams };

  return TblArtigo.findOne({
    where: whereCondition,
  });
};

const getImagemArtigoService = async (nomeImagem) => {
  try {
      const folderPath = process.env.IMAGE_PATH;


      // Construct the absolute folder path
      const absoluteFolderPath = path.isAbsolute(folderPath) ? folderPath : path.join(__dirname, folderPath);

      console.log(nomeImagem);
      // Construct the file path
      const filePath = path.join(absoluteFolderPath, nomeImagem);

      // Read the image file
      const image = await fs.readFile(filePath);

      return {
          success: true,
          data: image,
          message: 'Image retrieved successfully'
      };
  } catch (error) {
      console.error('Error retrieving image:', error);
      return {
          success: false,
          message: 'Error retrieving image'
      };
  }
};



const createArtigo = async (artigoData) => {
  return TblArtigo.create(artigoData);
};

const updateArtigo = async (id, artigoData) => {
  const artigo = await TblArtigo.findByPk(id);
  if (!artigo) {
    throw new Error("Artigo not found");
  }
  return artigo.update(artigoData);
};

const deleteArtigo = async (id) => {
  // Assuming TblArtigo is your Sequelize model
  const result = await TblArtigo.update(
    { bitEliminado: true },
    { where: { intId: id } }
  );

  // The 'result' object contains information about the operation
  const affectedRows = result[0];

  if (affectedRows === 0) {
    throw new Error("Artigo not found");
  }

  // You might want to return additional information if needed
  return { success: true, message: "Artigo soft deleted successfully" };
};

module.exports = {
  getAllArtigos,
  getArtigoById,
  createArtigo,
  updateArtigo,
  deleteArtigo,
  getImagemArtigoService,
};
