const { Op } = require("sequelize");
const dbSAPPS = require("../../helpers/db");
require("dotenv").config();

module.exports = {
    getAll,
    filter,
    option,
    count,
    create,
    update,
    enabled,
    delete: _delete,
};

async function getAll() {
    try {
        // Mengambil semua pengguna dan mengurutkannya berdasarkan kolom 'modified' secara menurun
        const vehicles = await dbSAPPS.Vehicle.findAll({
            order: [["modified", "DESC"]],
            include: [
                {
                    model: dbSAPPS.Company,
                    as: "company",
                    attributes: ["id", "name"],
                },
            ],
        });

        // Mengembalikan respons dengan status 200 OK
        return {
            vehicles,
            success: true,
            message: "vehicles loaded successfully!",
        };
    } catch (error) {
        // Menangani error dan mengembalikan respons dengan status 500 Internal Server Error
        const errorMessage = error.message || "Failed to load vehicles!";
        return {
            success: false,
            message: errorMessage,
        };
    }
}

async function filter(params) {
    // Membuat objek filter dengan validasi
    const filterConditions = {};

    if (params.license_plate) {
        filterConditions.license_plate = {
            [Op.like]: `%${params.license_plate}%`,
        };
    }

    if (params.enabled) {
        filterConditions.enabled = {
            [Op.eq]: params.enabled === "1" ? true : false,
        };
    }
    try {
        // Mencari pengguna berdasarkan filter conditions
        const vehicles = await dbSAPPS.Vehicle.findAll({
            where: filterConditions,
            order: [["modified", "DESC"]], // Opsional: Mengurutkan hasil berdasarkan kolom 'modified'
        });

        // Mengembalikan hasil pencarian
        return {
            success: true,
            vehicles,
            message: "vehicles loaded successfully!",
        };
    } catch (error) {
        // Logging error untuk keperluan debugging
        console.error("Error retrieving vehicles: ", error);
        const errorMessage =
            error.message || "Failed to retrieve vehicles. Please try again later.";
        // Mengembalikan respons dengan status 500 Internal Server Error
        return {
            success: false,
            message: errorMessage,
        };
    }
}

async function option() {
    try {
        // Mencari pengguna yang diaktifkan dengan atribut tertentu
        const vehicles = await dbSAPPS.Vehicle.findAll({
            attributes: ["id", "license_plate", "model", "odometer_value"],
            where: { enabled: true },
            order: [["license_plate", "ASC"]], // Opsional: Mengurutkan hasil berdasarkan
        });

        // Mengembalikan hasil pencarian
        return {
            success: true,
            vehicles,
            message: "vehicles loaded successfully!",
        };
    } catch (error) {
        // Logging error untuk keperluan debugging
        console.error("Error retrieving vehicles: ", error);
        const errorMessage =
            error.message || "Failed to retrieve vehicles. Please try again later.";
        // Mengembalikan respons dengan status 500 Internal Server Error
        return {
            success: false,
            message: errorMessage,
        };
    }
}

async function count() {
    try {
        // Menghitung jumlah pengguna yang diaktifkan
        const count = await dbSAPPS.Vehicle.count({
            where: { enabled: true },
        });

        // Mengembalikan hasil hitung
        return {
            success: true,
            count,
            message: "vehicles loaded successfully!",
        };
    } catch (error) {
        // Menangani error dan mengembalikan respons dengan status 500 Internal Server Error
        console.error("Error counting vehicles: ", error);
        return {
            success: false,
            message: "Failed to retrieve vehicles count. Please try again later.",
        };
    }
}

async function create(params) {
    try {
        // Validasi input
        if (!params.license_plate)
            return {
                success: false,
                message: "License plate is required!",
            };

        // Periksa apakah nama fakultas dgn company yg sama sudah digunakan
        const existingVehicle = await dbSAPPS.Vehicle.findOne({
            where: {
                license_plate: params.license_plate,
                company_id: params.company_id,
            },
        });

        if (existingVehicle)
            return {
                success: false,
                message: `Vehicle with "${params.license_plate}" in the same company is already taken.`,
            };

        if (!params.enabled) params.enabled = true;
        const newVehicle = await dbSAPPS.Vehicle.create(params);

        // Respons sukses
        return {
            success: true,
            message: "Vehicle data has been successfully added!",
            vehicle: newVehicle,
        };
    } catch (error) {
        // Menangani error dan mengembalikan respons dengan status 500 Internal Server Error
        const errorMessage =
            error.message || "An error occurred during create vehicle processing.";
        return {
            success: false,
            message: errorMessage,
        };
    }
}

async function update(id, params) {
    try {
        // Ambil dari database
        const vehicle = await dbSAPPS.Vehicle.findByPk(id);
        if (!vehicle)
            return {
                success: false,
                message: "Vehicle not found!",
            };

        // Validasi perubahan
        if (
            params.license_plate &&
            params.license_plate !== vehicle.license_plate
        ) {
            const existingVehicle = await dbSAPPS.Vehicle.findOne({
                where: {
                    license_plate: params.license_plate,
                    company_id: params.company_id,
                },
            });
            if (existingVehicle) {
                return {
                    success: false,
                    message: `Vehicle name "${params.license_plate}" is already taken. Try again!`,
                };
            }
        }

        // Perbarui data vehicle
        await vehicle.update(params);

        // Respons sukses
        return {
            success: true,
            message: "Data vehicle has been saved!",
        };
    } catch (error) {
        const errorMessage = error.message || "Failed to update vehicle data.";
        // Menangani error dan mengembalikan respons dengan status 500 Internal Server Error
        return {
            success: false,
            message: errorMessage,
        };
    }
}

async function enabled(id, params) {
    try {
        const vehicle = await dbSAPPS.Vehicle.findByPk(id);
        if (!vehicle)
            return {
                success: false,
                message: "Vehicle not found!",
            };

        const updateData = {};
        updateData.enabled = params.enabled;
        if (params.modified_by) updateData.modified_by = params.modified_by;
        if (params.modified) updateData.modified = params.modified;


        await vehicle.update(updateData);

        return {
            success: true,
            message: "Vehicle has been updated!",
        };
    } catch (error) {
        const errorMessage = error.message || "Failed to update Vehicle.";
        return {
            success: false,
            message: errorMessage,
        };
    }
}

async function _delete(id) {
    try {
        // Mengambil pengguna dari database
        const vehicle = await dbSAPPS.Vehicle.findByPk(id);
        if (!vehicle) return { success: false, message: "Vehicle not found!" };

        // Menghapus pengguna dari database
        await vehicle.destroy();

        // Respons sukses
        return {
            success: true,
            message: "Vehicle successfully deleted!",
        };
    } catch (error) {
        const errorMessage = error.message || "Failed to delete vehicle.";
        // Menangani error dan mengembalikan respons dengan status 500 Internal Server Error
        return {
            success: false,
            message: errorMessage,
        };
    }
}
