import { SelectQueryBuilder } from "typeorm";
import CommonHelper from "../helpers/common";
import { OrmHelper } from "../helpers/orm";
import { ItemMaster } from "entity";

export class ItemMasterModel {
    static async list(filter = {}): Promise<SelectQueryBuilder<any>> {
        const repo = OrmHelper.DB.getRepository(ItemMaster);
        let whereAttr: string[] = [];
        let whereVal: any = {};
        if (filter && Object.keys(filter).length > 0) {
            whereAttr = [...whereAttr, ...CommonHelper.handleQueryFilter(filter, "item_master").whereAttr];
            whereVal = { ...whereVal, ...CommonHelper.handleQueryFilter(filter, "item_master").whereVal };
        }

        var query = repo
        .createQueryBuilder("item_master")
        .leftJoinAndSelect("item_master.generic_name", "generic_name")
        .leftJoinAndSelect("item_master.type_detail", "type_detail")
        .leftJoinAndSelect("item_master.category", "category")
        .leftJoinAndSelect("item_master.item_class", "item_class")
        .leftJoinAndSelect("item_master.item_class_detail", "item_class_detail")
        .leftJoinAndSelect("item_master.status", "status")
        .leftJoinAndSelect("item_master.factory", "factory")
        // .leftJoinAndSelect("item_master.unit", "unit")
        if (whereAttr.length != 0) {
            query = query.where(whereAttr.join(" and "), whereVal);
        }

        return query;
    }
}