import Showroom from '../models/showroom.js';

export const getAll = async (req, res) => {
  try {
    const data = await Showroom.getAll();
    res.json(data);
  } catch (err) {
    console.error('Error:', err);
    res.status(500).json({ message: err.message });
  }
};

export const getOne = async (req, res) => {
  try {
    const data = await Showroom.getById(req.params.id);
    if (!data) return res.status(404).json({ message: 'Showroom item not found.' });
    res.json(data);
  } catch (err) {
    console.error('Error:', err);
    res.status(500).json({ message: err.message });
  }
};

export const create = async (req, res) => {
  try {
    const body = req.body;
    if (req.files?.image1) body.image1 = `/uploads/${req.files.image1[0].filename}`;
    if (req.files?.image2) body.image2 = `/uploads/${req.files.image2[0].filename}`;
    const id = await Showroom.create(body);
    const newItem = await Showroom.getById(id);
    res.status(201).json(newItem);
  } catch (err) {
    console.error('Error:', err);
    res.status(500).json({ message: err.message });
  }
};

export const update = async (req, res) => {
  try {
    const body = req.body;
    if (req.files?.image1) body.image1 = `/uploads/${req.files.image1[0].filename}`;
    if (req.files?.image2) body.image2 = `/uploads/${req.files.image2[0].filename}`;
    const affected = await Showroom.update(req.params.id, body);
    if (!affected) return res.status(404).json({ message: 'Showroom item not found.' });
    const updated = await Showroom.getById(req.params.id);
    res.json(updated);
  } catch (err) {
    console.error('Error:', err);
    res.status(500).json({ message: err.message });
  }
};

export const remove = async (req, res) => {
  try {
    const affected = await Showroom.remove(req.params.id);
    if (!affected) return res.status(404).json({ message: 'Showroom item not found.' });
    res.json({ message: 'Showroom item deleted.' });
  } catch (err) {
    console.error('Error:', err);
    res.status(500).json({ message: err.message });
  }
};