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

export class CrudService {
    static async getMany(table, limit, offset) {
        const [rows] = await pool.execute(`SELECT * FROM ${table} LIMIT ? OFFSET ?`, [limit, offset]);
        return rows;
    }

    static async create(table, body) {
        if (!body.id) {
            const [[{ uuid }]] = await pool.execute('SELECT UUID() as uuid');
            body.id = uuid;
        }
        const keys = Object.keys(body);
        const values = Object.values(body);
        const placeholders = keys.map(() => '?').join(', ');
        const escapedKeys = keys.map(k => `\`${k}\``);
        const sql = `INSERT INTO ${table} (${escapedKeys.join(', ')}) VALUES (${placeholders})`;
        await pool.execute(sql, values.map(v => (v !== null && typeof v === 'object') ? JSON.stringify(v) : v));
        return { id: body.id, ...body };
    }

    static async update(table, id, body) {
        const keys = Object.keys(body);
        const values = Object.values(body);
        const setClause = keys.map(key => `\`${key}\` = ?`).join(', ');
        const sql = `UPDATE ${table} SET ${setClause} WHERE id = ?`;
        await pool.execute(sql, [...values.map(v => (v !== null && typeof v === 'object') ? JSON.stringify(v) : v), id]);
    }

    static async remove(table, id) {
        await pool.execute(`DELETE FROM ${table} WHERE id = ?`, [id]);
    }
}
