const fs = require("fs");
const path = require("path");
const Review = require("../../models/home/reviewModel");
require("dotenv").config();
const BASE_URL = process.env.BASE_URL;

const reviewController = {
  create: async (req, res) => {
    try {
      const { reviewer_title, reviewer_company_name, reviewer_service_name, review_text , show_on_home } = req.body;
      if (!req.file || !reviewer_title || !reviewer_company_name || !reviewer_service_name || !review_text) {
        return res.status(400).json({ success: false, message: "All fields are required including image." });
      }

      const imagePath = req.file.path.replace(/\\/g, "/");
      const data = await Review.create({
        reviewer_title,
        reviewer_company_name,
        reviewer_service_name,
        review_text,
        reviewer_thumbnail: imagePath,
        show_on_home,
        pages: req.body.pages ? JSON.parse(req.body.pages) : []
      });

      res.json({ success: true, message: "Review created successfully", data });
    } catch (err) {
      res.status(500).json({ success: false, message: "Server Error", error: err.message });
    }
  },

  getAll: async (req, res) => {
    try {
      const data = await Review.findAll();
      const updatedData = data.map((review) => ({
        ...review.toJSON(),
        reviewer_thumbnail: `${BASE_URL}${review.reviewer_thumbnail}`,
        pages: JSON.parse(review.pages)
      }));
      res.json({ success: true, data: updatedData });

    } catch (err) {
      res.status(500).json({ success: false, message: "Server Error", error: err.message });
    }
  },

  getSingle: async (req, res) => {
    try {
      const data = await Review.findByPk(req.params.id);
      if (!data) {
        return res.status(404).json({ success: false, message: "Review not found" });
      }

      res.json({
        success: true,
        data: {
          ...data.toJSON(),
          reviewer_thumbnail: `${BASE_URL}${data.reviewer_thumbnail}`,
        },
      });
    } catch (err) {
      res.status(500).json({ success: false, message: "Server Error", error: err.message });
    }
  },

  update: async (req, res) => {
    try {
      const review = await Review.findByPk(req.params.id);
      if (!review) {
        return res.status(404).json({ success: false, message: "Review not found" });
      }

      let thumbnailPath = review.reviewer_thumbnail;

      if (req.file) {
        // Remove old file
        if (fs.existsSync(thumbnailPath)) {
          fs.unlinkSync(thumbnailPath);
        }
        thumbnailPath = req.file.path.replace(/\\/g, "/");
      }

      const { reviewer_title, reviewer_company_name, reviewer_service_name, show_on_home, review_text } = req.body;

      await review.update({
        reviewer_title,
        reviewer_company_name,
        reviewer_service_name,
        review_text,
        show_on_home,
        reviewer_thumbnail: thumbnailPath,
        pages: req.body.pages ? JSON.parse(req.body.pages) : []
      });

      res.json({ success: true, message: "Review updated", data: review });
    } catch (err) {
      res.status(500).json({ success: false, message: "Server Error", error: err.message });
    }
  },

  delete: async (req, res) => {
    try {
      const review = await Review.findByPk(req.params.id);
      if (!review) {
        return res.status(404).json({ success: false, message: "Review not found" });
      }

      if (fs.existsSync(review.reviewer_thumbnail)) {
        fs.unlinkSync(review.reviewer_thumbnail);
      }

      await review.destroy();
      res.json({ success: true, message: "Review deleted" });
    } catch (err) {
      res.status(500).json({ success: false, message: "Server Error", error: err.message });
    }
  },
};

module.exports = reviewController;
