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

class ConstructorService {
    createPack(data) {
        return new Promise((res, rej) => {

            if (data.type === "house") {
                const sql = `
                    INSERT INTO house (
                        title, number, points, points_number, geo, osm_id, settlement, created_at
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`;

                db.run(sql, [
                    data.title,
                    data.number,
                    JSON.stringify(data.points),
                    JSON.stringify(data.points_number),
                    JSON.stringify(data.geo),
                    JSON.stringify(data.osm_id),
                    data.settlement,
                    Math.floor(Date.now())
                ], function (err) {
                    if (err) {
                        console.error(err.message);
                        return res(false);
                    }
                    if (this.changes === 0) {
                        return res(false);
                    }

                    const houseId = this.lastID;

                    const entranceStmt = db.prepare(`
                        INSERT INTO entrance (
                            house_id, entrance_number, title, created_at
                        ) VALUES (?, ?, ?, ?)`);

                    const apartmentStmt = db.prepare(`
                        INSERT INTO apartments (
                            entrance_id, apartment_number, title, floors_number
                        ) VALUES (?, ?, ?, ?)`);

                    let pendingEntrances = data.entrances.length;
                    const entranceIdMap = {};

                    if (pendingEntrances === 0) return finalize();

                    // Вставляем подъезды
                    data.entrances.forEach(entrance => {
                        entranceStmt.run(
                            houseId,
                            Number(entrance.entrance_number),
                            entrance.title,
                            Math.floor(Date.now()),
                            function (err) {
                                if (err) {
                                    console.error(err.message);
                                    return res(false);
                                }

                                const entranceID = this.lastID;
                                entranceIdMap[entrance.entrance_number] = entranceID;

                                // Вставляем квартиры данного подъезда
                                let pendingApartments = entrance.apartments.length;
                                if (pendingApartments === 0) {
                                    if (--pendingEntrances === 0) finalize();
                                    return;
                                }

                                entrance.apartments.forEach(apartment => {
                                    apartmentStmt.run(
                                        entranceID,
                                        Number(apartment.apartment_number),
                                        apartment.title,
                                        Number(apartment.floors_number),
                                        function (err) {
                                            if (err) console.error(err.message);

                                            if (--pendingApartments === 0) {
                                                if (--pendingEntrances === 0) finalize();
                                            }
                                        }
                                    );
                                });
                            }
                        );
                    });

                    genCards({type: "house", id: houseId});

                    function finalize() {
                        entranceStmt.finalize();
                        apartmentStmt.finalize();
                        res({ status: "ok", id: houseId });
                    }
                });

            } else if (data.type === "homestead") {
                const sql = `
                    INSERT INTO homestead (
                        title, number, zoom, points, geo, osm_id, settlement, created_at
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                `;

                db.run(sql, [
                    data.title,
                    data.number,
                    Number(data.zoom),
                    JSON.stringify(data.points),
                    JSON.stringify(data.geo),
                    JSON.stringify(data.osm_id),
                    data.settlement,
                    Math.floor(Date.now())
                ], function (err) {
                    if (err) {
                        console.error(err.message);
                        return res(false);
                    }
                    if (this.changes === 0) {
                        return res(false);
                    }

                    const homesteadId = this.lastID;

                    const buildingStmt = db.prepare(`
                        INSERT INTO buildings (
                            homestead_id, title, geo
                        ) VALUES (?, ?, ?)
                    `);

                    let pendingBuildings = data.buildings.length;

                    if (pendingBuildings === 0) return finalize();
                    


                    data.buildings.forEach(building => {
                        buildingStmt.run(
                            homesteadId,
                            building.title,
                            JSON.stringify(building.geo),
                            function (err) {
                                if (err) {
                                    console.error(err.message);
                                    return res(false);
                                }

                                if (--pendingBuildings === 0) finalize();
                            }
                        );
                    });

                    genCards({type: "homestead", id: homesteadId});

                    function finalize() {
                        buildingStmt.finalize();
                        res({ status: "ok", id: homesteadId });
                    }
                });
            } else {
                return res(false);
            }
        });
    }
}

module.exports = new ConstructorService();