import sequelize from "../sequelize.js";

export const list = async (params) => {
    try {
        const { offset, limit, search, ...otherParams } = params;

        const numericOffset = offset ? parseInt(offset, 10) : 0;
        const numericLimit = limit ? parseInt(limit, 10) : 1000;

        const rows = await sequelize.models.customers.findAll({
            where: { ...otherParams },
            offset: numericOffset,
            limit: numericLimit,
        });

        return { rows };
    } catch (error) {
        console.error('Error fetching:', error);
        throw new Error('Failed to fetch');
    }
};

export const create = async (params) => {
    try {
        await sequelize.models.customers.create(params);
        return true;
    } catch (error) {
        console.error('Error creating:', error);
        throw new Error('Failed to create');
    }
};

export const update = async (params) => {
    try {
        const { where, updates } = params;
        if (!where || !updates) {
            throw new Error('Missing required parameters: where and updates');
        }

        return await sequelize.models.customers.update(updates, {
            where
        });
    } catch (error) {
        console.error('Error updating:', error);
        throw new Error('Failed to update');
    }
};

export const remove = async (params) => {
    try {
        const { ...otherParams } = params;

        return await sequelize.models.customers.destroy({
            where: { ...otherParams },
        });
    } catch (error) {
        console.error('Error deleting:', error);
        throw new Error('Failed to delete');
    }
};
