const db = require("../config/db");

class historyApartmentService {
    getList(limit) {
        return new Promise((res, rej) => {
            let sql = `
                SELECT 
                    ah.*,
                    s.name AS sheep_name,
                    s.group_id AS sheep_group_id,
                    s.icon AS sheep_icon,
                    h.title AS house_title,
                    h.number AS house_number,
                    h.id AS house_id,
                    e.title AS entrance_title,
                    a.title AS apartment_title
                    FROM 
                        apartments_history ah
                    LEFT JOIN 
                        sheeps s ON s.id = ah.sheep_id
                    LEFT JOIN 
                        apartments a ON a.id = ah.apartments_id
                    LEFT JOIN 
                        entrance e ON e.id = a.entrance_id
                    LEFT JOIN 
                        house h ON h.id = e.house_id
                    ORDER BY 
                        ah.id DESC
                    LIMIT ${limit ?? 100};
            `;

            db.all(sql, (err, rows) => {
                if (err) {
                    console.error(err.message);
                    return res(false);
                } else {
                    let data = rows.map((row) => {
                        return {
                            "id": Number(row.id),
                            "apartments_id": Number(row.apartments_id),
                            "house_id": Number(row.house_id),
                            "address": {
                                "house": {
                                    "title": row.house_title,
                                    "number": row.house_number
                                },
                                "entrance": row.entrance_title,
                                "apartment": row.apartment_title
                            },
                            "status": Number(row.status),
                            "description": row.description,
                            "sheep": {
                                "id": Number(row.sheep_id),
                                "name": row.sheep_name,
                                "group_id": Number(row.sheep_group_id),
                                "icon": row.sheep_icon
                            },
                            "created_at": Number(row.created_at)
                        }
                    })

                    return res(data);
                }
            });
        });
    }
}

module.exports = new historyApartmentService();