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

class ProductService {
    async create(groupid, localid, abstract_product_id, amount, date_of_production, expiry_date) {
        await db.query("INSERT INTO products (group_id, local_id, abstract_product_id, amount, date_of_production, expiry_date) VALUES ($1, $2, $3, $4, $5, $6)", [groupid, localid, abstract_product_id, amount, date_of_production, expiry_date])
            .catch((e) => {
                errorHandler(e, "Abstract Product")
            });
    }

    async updateAbstractProductId(groupId, localId, abstract_product_id) {
        await db.query("UPDATE products SET abstract_product_id = $1 WHERE group_id = $2 AND local_id = $3", [abstract_product_id, groupId, localId])
            .catch((e) => {
                errorHandler(e, "abstract product id")
            });

    }

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

    async updateDateOfProduction(groupId, localId, date_of_production) {
        await db.query("UPDATE products SET date_of_production = $1 WHERE group_id = $2 AND local_id = $3", [date_of_production, groupId, localId])
            .catch((e) => {
                errorHandler(e, "date of production")
            });
    }

    async updateExpiryDate(groupId, localId, expiry_date) {
        await db.query("UPDATE products SET expiry_date = $1 WHERE group_id = $2 AND local_id = $3", [expiry_date, groupId, localId])
            .catch((e) => {
                errorHandler(e, "expiry date")
            });
    }

    async getAll(groupId) {
        let result = (await db.query("SELECT local_id, abstract_product_id, amount, date_of_production, expiry_date FROM 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 products WHERE group_id = $1 AND local_id = $2", [groupId, localId])).rowCount;
        if (!result) return false;
        return true;
    }
};

export default new ProductService();