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

export class PatientGuarantorModel {
    static async list(filterObj = {}, filterAny: string = ""): Promise<SelectQueryBuilder<any>> {
        const repo = OrmHelper.DB.getRepository(PatientGuarantor);
        let whereAttr = [];
        let whereVal: any = {};
        if (filterObj) {
            const filterResult = CommonHelper.handleQueryFilter(filterObj);
            whereAttr = [...whereAttr, ...filterResult.whereAttr];
            whereVal = { ...whereVal, ...filterResult.whereVal };
        }

        if (filterAny && filterAny !== "" && filterAny !== null && filterAny !== undefined) {
            const filterResult = CommonHelper.handleFilter({
                filter: JSON.stringify({ any: filterAny }),
                col_any_eq: [],
                col_any_like: ["guarantor_name", "phone"],
            });

            if (filterResult.whereAttr && filterResult.whereAttr !== "") {
                whereAttr = [...whereAttr, filterResult.whereAttr];
                whereVal = { ...whereVal, ...filterResult.whereVal };
            }
        }

        var query = repo.createQueryBuilder("patient_guarantor")
        .leftJoinAndSelect("patient_guarantor.patient_group", "patient_group")
        .leftJoinAndSelect("patient_guarantor.faretype", "faretype")
        .leftJoinAndSelect("patient_guarantor.administrativu", "administrativu")
        .leftJoinAndSelect("patient_guarantor.suco", "suco")
        .leftJoinAndSelect("patient_guarantor.aldeia", "aldeia")
        .leftJoinAndSelect("patient_guarantor.munisipo", "munisipo");
        if (whereAttr.length != 0) {
            query = query.where(whereAttr.join(" and "), whereVal);
        }

        return query;
    }
}