import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import productService from '../services/productService.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

export const getAll = async (req, res, next) => {
  try {
    const result = await productService.getAllProducts(req.query);
    res.json({ success: true, data: result });
  } catch (error) {
    next(error);
  }
};

export const getById = async (req, res, next) => {
  try {
    const product = await productService.getProductById(req.params.id);
    res.json({ success: true, data: product });
  } catch (error) {
    next(error);
  }
};

export const getByBarcode = async (req, res, next) => {
  try {
    const result = await productService.findByBarcode(req.params.barcode);
    res.json({ success: true, data: result });
  } catch (error) {
    next(error);
  }
};

export const create = async (req, res, next) => {
  try {
    const data = { ...req.body };
    if (req.file) {
      data.image = `/uploads/products/${req.file.filename}`;
    }
    if (data.discountRules && typeof data.discountRules === 'string') {
      try { data.discountRules = JSON.parse(data.discountRules); } catch {}
    }
    const product = await productService.createProduct(data, req);
    res.status(201).json({ success: true, message: 'Product created', data: product });
  } catch (error) {
    next(error);
  }
};

export const update = async (req, res, next) => {
  try {
    const data = { ...req.body };
    if (req.file) {
      data.image = `/uploads/products/${req.file.filename}`;
    }
    if (data.discountRules && typeof data.discountRules === 'string') {
      try { data.discountRules = JSON.parse(data.discountRules); } catch {}
    }
    const product = await productService.updateProduct(req.params.id, data, req);
    res.json({ success: true, message: 'Product updated', data: product });
  } catch (error) {
    next(error);
  }
};

export const remove = async (req, res, next) => {
  try {
    const product = await productService.getProductById(req.params.id);
    if (product && product.image) {
      const imagePath = path.join(__dirname, '../../uploads/products', path.basename(product.image));
      fs.unlink(imagePath, () => {});
    }
    await productService.deleteProduct(req.params.id, req);
    res.json({ success: true, message: 'Product deleted' });
  } catch (error) {
    next(error);
  }
};

export const deleteImage = async (req, res, next) => {
  try {
    const product = await productService.getProductById(req.params.id);
    if (!product) {
      return res.status(404).json({ success: false, message: 'Product not found' });
    }
    if (product.image) {
      const imagePath = path.join(__dirname, '../../uploads/products', path.basename(product.image));
      fs.unlink(imagePath, () => {});
      await productService.updateProduct(req.params.id, { image: '' });
    }
    res.json({ success: true, message: 'Image removed' });
  } catch (error) {
    next(error);
  }
};
