import Products from '../models/products.js';

// GET /api/products
export const getAll = async (req, res) => {
  try {
    const data = await Products.getAll();
    res.json(data);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

// GET /api/products/category/:slug
export const getByCategory = async (req, res) => {
  try {
    const data = await Products.getByCategory(req.params.slug);
    res.json(data);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

// GET /api/products/:id
export const getOne = async (req, res) => {
  try {
    const data = await Products.getById(req.params.id);
    if (!data) return res.status(404).json({ message: 'Product not found.' });
    res.json(data);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

// POST /api/products
export const create = async (req, res) => {
  try {
    const body = req.body;
    if (body.features && typeof body.features === 'string') {
      body.features = JSON.parse(body.features);
    }
    // ✅ Save only filename — NOT "public/uploads/filename"
    if (req.files?.image1) body.image1 = req.files.image1[0].filename;
    if (req.files?.image2) body.image2 = req.files.image2[0].filename;
    await Products.create(body);
    res.status(201).json({ message: 'Product created.' });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

// PUT /api/products/:id
export const update = async (req, res) => {
  try {
    const body = req.body;
    if (body.features && typeof body.features === 'string') {
      body.features = JSON.parse(body.features);
    }
    // ✅ Save only filename — NOT "public/uploads/filename"
    if (req.files?.image1) body.image1 = req.files.image1[0].filename;
    if (req.files?.image2) body.image2 = req.files.image2[0].filename;
    const affected = await Products.update(req.params.id, body);
    if (!affected) return res.status(404).json({ message: 'Product not found.' });
    res.json({ message: 'Product updated.' });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

// DELETE /api/products/:id
export const remove = async (req, res) => {
  try {
    const affected = await Products.remove(req.params.id);
    if (!affected) return res.status(404).json({ message: 'Product not found.' });
    res.json({ message: 'Product deleted.' });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};