import { Injectable, Logger } from "@nestjs/common";
import { EntityManager } from "typeorm";
import { randomCodeChars } from "../../types/constants";

@Injectable()
export default class HelperProvider {

    private logger: Logger = new Logger(HelperProvider.name);

    constructor(private readonly entityManager: EntityManager){}

    /**
     * Get stock 
     * @param idArticle 
     * @param idStore 
     * @param idStorage 
     * @returns 
     */
    async getStock(idArticle: number, idStore?: number, idStorage?: number): Promise<number>{

        let stock: number = 0;

        try{

            const wheres: string[] = [];
            const values: number[] = [idArticle];

            if(idStore){
                wheres.push(`id_store = ?`);
                values.push(idStore);
            }
            if(idStorage){
                wheres.push(`id_storage = ?`);
                values.push(idStorage);
            }

            const where = wheres.length > 0 ? ` AND ${wheres.join(" AND ")}` : "";

            const result = 
                await this.entityManager.query(
                    `SELECT IFNULL((SUM(charge) - SUM(discharge)), 0) stock FROM movement WHERE id_article = ? ${where} LIMIT 1`,
                    values
                );

            if(result.length > 0){
                stock = parseFloat( (result[0]['stock'] ?? 0).toString() );
            }

        }catch(e: any){
            this.logger.error(e.message);
        }

        return stock;
    }

    /**
     * Generate random codes
     * @param length 
     * @returns 
     */
    generateRandomCode(length: number = 8): string{
        let code = "";
        for(let i = 0; i < length; i++){
            code += randomCodeChars.charAt(Math.floor(Math.random() * randomCodeChars.length));
        }
        return code;
    }


}