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

export class OrderService {
    static async getOrders(limit, offset) {
        const [orders] = await pool.execute('SELECT * FROM orders ORDER BY created_at DESC LIMIT ? OFFSET ?', [limit, offset]);
        if (orders.length === 0) return [];
        
        const orderIds = orders.map(o => o.id);
        const [steps] = await pool.query('SELECT * FROM production_steps WHERE order_id IN (?)', [orderIds]);
        
        return orders.map(order => ({
            ...order,
            production_steps: (steps || []).filter(step => step.order_id === order.id),
            productionSteps: (steps || []).filter(step => step.order_id === order.id)
        }));
    }

    static async createOrder(orderData, steps) {
        const keys = Object.keys(orderData);
        const values = Object.values(orderData);
        const placeholders = keys.map(() => '?').join(', ');
        const escapedKeys = keys.map(k => `\`${k}\``);
        
        const sql = `INSERT INTO orders (${escapedKeys.join(', ')}) VALUES (${placeholders})`;
        await pool.execute(sql, values.map(v => (v !== null && typeof v === 'object') ? JSON.stringify(v) : v));

        if (steps && Array.isArray(steps)) {
            for (const step of steps) {
                const sKeys = Object.keys(step);
                const sValues = Object.values(step);
                const sPlaceholders = sKeys.map(() => '?').join(', ');
                const sEscapedKeys = sKeys.map(k => `\`${k}\``);
                const sSql = `INSERT INTO production_steps (${sEscapedKeys.join(', ')}) VALUES (${sPlaceholders})`;
                await pool.execute(sSql, sValues.map(v => (v !== null && typeof v === 'object') ? JSON.stringify(v) : v));
            }
        }
    }
}
