import db from '../config/db.js';

const Products = {
  async getAll() {
    const [rows] = await db.query('SELECT * FROM products ORDER BY sort_order ASC');
    return rows;
  },

  async getByCategory(category_slug) {
    const [rows] = await db.query(
      'SELECT * FROM products WHERE category_slug = ? ORDER BY sort_order ASC',
      [category_slug]
    );
    return rows;
  },

  async getById(id) {
    const [rows] = await db.query('SELECT * FROM products WHERE id = ?', [id]);
    return rows[0] || null;
  },

  async create(data) {
    const { category_slug, name, image1, image2, description, features, material, origin, sort_order } = data;
    const [result] = await db.query(
      `INSERT INTO products
        (category_slug, name, image1, image2, description, features, material, origin, sort_order)
       VALUES (?,?,?,?,?,?,?,?,?)`,
      [
        category_slug, name,
        image1 || '', image2 || '',
        description || '',
        JSON.stringify(features || []),
        material || '', origin || '',
        sort_order || 0,
      ]
    );
    return result.insertId;
  },

  async update(id, data) {
    const { category_slug, name, image1, image2, description, features, material, origin, sort_order } = data;
    const [result] = await db.query(
      `UPDATE products SET
        category_slug=?, name=?, image1=?, image2=?,
        description=?, features=?, material=?, origin=?, sort_order=?
       WHERE id=?`,
      [
        category_slug, name,
        image1 || '', image2 || '',
        description || '',
        JSON.stringify(features || []),
        material || '', origin || '',
        sort_order || 0, id,
      ]
    );
    return result.affectedRows;
  },

  async remove(id) {
    const [result] = await db.query('DELETE FROM products WHERE id = ?', [id]);
    return result.affectedRows;
  },
};

export default Products;