import db from '../db.js';
import statuses from '../utils/status.js';
import errorHandler from '../utils/pgerrorhandler.js';

class AbstractProductService {
    async create(groupid, localid, barcode, name, net_weight, image_filename, category, unit) {
        await db.query("INSERT INTO abstract_products (group_id, local_id, barcode, name, net_weight, image_filename, category, unit) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)", [groupid, localid, barcode, name, net_weight, image_filename, category, unit])
            .catch((e) => {
                errorHandler(e, "abstract product")
            });
    }

    async updateBarcode(groupId, localId, barcode) {
        await db.query("UPDATE abstract_products SET barcode = $1 WHERE group_id = $2 AND local_id = $3", [barcode, groupId, localId])
            .catch((e) => {
                errorHandler(e, "barcode")
            });
    }

    async updateName(groupId, localId, name) {
        await db.query("UPDATE abstract_products SET name = $1 WHERE group_id = $2 AND local_id = $3", [name, groupId, localId])
            .catch((e) => {
                errorHandler(e, "name")
            });
    }

    async updateNetWeight(groupId, localId, net_weight) {
        await db.query("UPDATE abstract_products SET net_weight = $1 WHERE group_id = $2 AND local_id = $3", [net_weight, groupId, localId]
            .catch((e) => {
                errorHandler(e, "net weight")
            }));
    }

    async updateImageFilename(groupId, localId, image_filename) {
        await db.query("UPDATE abstract_products SET image_filename = $1 WHERE group_id = $2 AND local_id = $3", [image_filename, groupId, localId])
            .catch((e) => {
                errorHandler(e, "image filename")
            });
    }

    async updateCategory(groupId, localId, category) {
        await db.query("UPDATE abstract_products SET category = $1 WHERE group_id = $2 AND local_id = $3", [category, groupId, localId])
            .catch((e) => {
                errorHandler(e, "category")
            });
    }

    async updateUnit(groupId, localId, unit) {
        await db.query("UPDATE abstract_products SET unit = $1 WHERE group_id = $2 AND local_id = $3", [unit, groupId, localId])
            .catch((e) => {
                errorHandler(e, "unit")
            });
    }

    async getAll(groupId) {
        let result = (await db.query("SELECT local_id, barcode, name, net_weight, image_filename, category, unit FROM abstract_products WHERE group_id = $1", [groupId])).rows;
        if (!result) return statuses.not_found;
        return result;
    }

    async exists(groupId, localId) {
        let result = (await db.query("SELECT * FROM abstract_products WHERE group_id = $1 AND local_id = $2", [groupId, localId])).rowCount;
        if (!result) return false;
        return true;
    }
};

export default new AbstractProductService();