const { getDatabase } = require('../config/database');

const AssetMovement = {
    getAll({ limit = 200, asset_id } = {}) {
        const db = getDatabase();
        let q = `
            SELECT m.*,
                a.name AS asset_name, a.inventory_number, a.serial_number,
                u.first_name || ' ' || u.last_name AS performed_by_name,
                au.first_name || ' ' || au.last_name AS assigned_user_name,
                fl.name AS from_location_name,
                tl.name AS to_location_name
            FROM asset_movements m
            LEFT JOIN assets a ON m.asset_id = a.id
            LEFT JOIN users u ON m.performed_by = u.id
            LEFT JOIN users au ON m.assigned_user_id = au.id
            LEFT JOIN warehouse_locations fl ON m.from_location_id = fl.id
            LEFT JOIN warehouse_locations tl ON m.to_location_id = tl.id
        `;
        const params = [];
        if (asset_id) {
            q += ` WHERE m.asset_id = ?`;
            params.push(asset_id);
        }
        q += ` ORDER BY m.created_at DESC LIMIT ?`;
        params.push(limit);
        return db.prepare(q).all(...params);
    },

    getById(id) {
        const db = getDatabase();
        return db.prepare(`
            SELECT m.*,
                a.name AS asset_name, a.inventory_number,
                u.first_name || ' ' || u.last_name AS performed_by_name,
                fl.name AS from_location_name,
                tl.name AS to_location_name
            FROM asset_movements m
            LEFT JOIN assets a ON m.asset_id = a.id
            LEFT JOIN users u ON m.performed_by = u.id
            LEFT JOIN warehouse_locations fl ON m.from_location_id = fl.id
            LEFT JOIN warehouse_locations tl ON m.to_location_id = tl.id
            WHERE m.id = ?
        `).get(id);
    },

    create(data) {
        const db = getDatabase();
        const result = db.prepare(`
            INSERT INTO asset_movements
                (asset_id, type, from_location_id, to_location_id, assigned_user_id, ticket_id, reason, notes, performed_by)
            VALUES
                (@asset_id, @type, @from_location_id, @to_location_id, @assigned_user_id, @ticket_id, @reason, @notes, @performed_by)
        `).run({
            asset_id:         data.asset_id,
            type:             data.type,
            from_location_id: data.from_location_id || null,
            to_location_id:   data.to_location_id   || null,
            assigned_user_id: data.assigned_user_id  || null,
            ticket_id:        data.ticket_id         || null,
            reason:           data.reason            || '',
            notes:            data.notes             || '',
            performed_by:     data.performed_by,
        });
        return this.getById(result.lastInsertRowid);
    },

    getRecentByAsset(asset_id, limit = 20) {
        return this.getAll({ asset_id, limit });
    },
};

module.exports = AssetMovement;
