import { Response, NextFunction, Application } from "express";
import { Request } from "express-jwt";
import { ReturnHelper } from "../helpers/express/return";
import { OrmHelper } from "../helpers/orm";
import Joi from "joi";
import { ILogObj, Logger } from "tslog";
import { Language } from "../langs/lang";
import { PatientGuarantor, Paging } from "entity";
import CommonHelper from "../helpers/common";
import * as fastcsv from 'fast-csv';
import dayjs from "dayjs";
import { PatientGuarantorModel } from "../model/patient_guarantor";

const log: Logger<ILogObj> = new Logger({ name: '[PatientGuarantorController]', type: 'pretty' });

export class PatientGuarantorController {
    static async list(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
        /*
            #swagger.tags = ['PatientGuarantor']
            #swagger.security = [{ "bearerAuth": [] }]
            #swagger.parameters['filter'] = { description: '', in: 'query', type: 'string' }
            #swagger.parameters['limit'] = { in: 'query', required: true, type: 'number' }
            #swagger.parameters['page'] = { in: 'query', required: true, type: 'number' }
            #swagger.parameters['with_deleted'] = { in: 'query', required: true, type: 'boolean' }
            #swagger.parameters['order_field'] = { in: 'query', required: true, type: 'string' }
            #swagger.parameters['order_direction'] = { in: 'query', required: true, schema: { '@enum': ['ASC', 'DESC'] } }
        */
        try {
            const schema = Joi.object().keys({
                filter: Joi.string().allow("").optional().label("Filter"),
                page: Joi.number().required().min(1).label("Page"),
                limit: Joi.number().required().min(1).label("Limit"),
                with_deleted: Joi.bool().required().label("With Deleted"),
                order_field: Joi.string().required().label("Order Field"),
                order_direction: Joi.string().allow("asc", "desc").required().label("Order Direction"),
            });

            let param: Paging = await schema.validateAsync(req.query);

            let filter = param.filter && param.filter !== "" ? JSON.parse(param.filter) : {};
            let filterAny = filter.any && filter.any !== "" ? filter.any : "";

            let filterObj = { ...filter } as any;
            delete filterObj.any;
            filterObj = { ...filterObj };

            var query = await PatientGuarantorModel.list(filterObj, filterAny);

            const offset = (param.page - 1) * param.limit;
            let limit = param.limit;

            const res_count = query;
            const res_list = query
                .orderBy("patient_guarantor." + param.order_field, param.order_direction)
                .offset(offset)
                .limit(limit);

            if (param.with_deleted) {
                res_count.withDeleted();
                res_list.withDeleted();
            }

            const current_page = param.page;
            const total_count_data = await res_count.getCount();
            const list_data = await res_list.getMany();
            const count_data = CommonHelper.countObject(list_data);

            return ReturnHelper.successResponselist(res, 200, Language.lang.success_view, count_data, current_page, total_count_data, list_data);
        } catch (e: unknown) {
            log.error(e);
            const err = e as Error;
            return ReturnHelper.errorResponse(res, 400, 401, Language.lang.failed_view, err.message);
        }
    }

    static async export(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
        /*
        #swagger.tags = ['PatientGuarantor']
        #swagger.security = [{
            "bearerAuth": []
        }]
        #swagger.parameters['filter'] = {
            description: 'Filter with 2 format : <ul><li>Simple format use text plaint will filter eq:code or like %name%</li><li>Advance format using field existing {status:\'Y\', any:\'SAME AS PLAINT LOGIC\', etc...}</li></ul>',
            in: 'query',
            type: 'string'
        }
        #swagger.parameters['filter'] = {
            in: 'query',
            type: 'string'
        }
        #swagger.parameters['order_field'] = {
            in: 'query',
            required: true,
            type: 'string'
        }
        #swagger.parameters['order_direction'] = {
            in: 'query',
            required: true,
            schema: {
                '@enum': ['ASC', 'DESC']
            }
        }
        */

        try {
            const schema = Joi.object().keys({
                filter: Joi.string().allow('').optional().label('Filter'),
                order_field: Joi.string().required().label('Order Field'),
                order_direction: Joi.string().allow('asc', 'desc').required().label('Order Direction'),
            });

            const param: Paging = await schema.validateAsync(req.query);

            let filter = param.filter && param.filter !== "" ? JSON.parse(param.filter) : {};

            var query = await PatientGuarantorModel.list(filter);
            const data = await query.getMany();

            const filename = "patient_guarantor.csv";

            res.setHeader('Content-Type', 'text/csv');
            res.setHeader('Content-Disposition', 'attachment; filename=' + filename);

            const csvStream = fastcsv.format({
                headers: true,
                writeHeaders: true,
                transform: (row: PatientGuarantor): any => ({
                    ...row,
                    created_at: dayjs(row.created_at).format('DD-MM-YYYY HH:MM:ss'),
                })
            });
            csvStream.pipe(res);

            const limit = 50;

            const fetchAndWrite = async (page: any) => {

                if (CommonHelper.countObject(data) === 0) {
                    csvStream.end();
                } else {
                    data.forEach((item: any) => csvStream.write(item));

                    if (CommonHelper.countObject(data) == limit) {
                        fetchAndWrite(page + 1);
                    } else {
                        csvStream.end();
                    }
                }
            };

            fetchAndWrite(1);
        } catch (e: unknown) {
            log.error(e);
            const err = e as Error;

            return ReturnHelper.errorResponse(res, 400, 401, Language.lang.failed_view, err.message);
        }
    }

    static async create(req: Request, res: Response, next: NextFunction): Promise<Response> {
        /*
        #swagger.tags = ['PatientGuarantor']
        #swagger.security = [{
            "bearerAuth": []
        }]
        
        #swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                         $ref: "#/components/schemas/patient_guarantor"
                    }  
                }
            }
        }
        */
        try {
            const schema = Joi.object().keys({
                guarantor_name: Joi.string().max(256).required().label('Guarantor Name'),
                phone: Joi.string().max(15).required().label('Phone'),
                // province: Joi.string().max(128).required().label('Province'),
                // city: Joi.string().max(128).required().label('City'),
                munisipo: Joi.string().allow(null, "").label("Munisipo ID"),
                administrativu: Joi.string().allow(null, "").label("Administrativu ID"),
                aldeia: Joi.string().allow(null, "").label("Aldeia ID"),
                suco: Joi.string().allow(null, "").label("Suco ID"),
                // zip_code: Joi.string().max(10).required().label('Zip Code'),
                agreement_no: Joi.string().max(50).required().label('Agreement No.'),
                agreement_desc: Joi.string().max(512).optional().label('Agreement Description'),
                patient_group_id: Joi.string().guid({ version: 'uuidv4' }).required().label('Patient Group'),
                faretype: Joi.string().guid({ version: 'uuidv4' }).required().label('Fare Type'),
                maximalliability: Joi.number().optional().label('Maximal Liability'),
                is_default: Joi.bool().optional().default(false).label('Is Default'),
                is_full_paid: Joi.bool().optional().default(false).label('Is Full Paid'),
            });

            const param: any = await schema.validateAsync(req.body);

            if (param.is_default === true) {
                await OrmHelper.DB.getRepository(PatientGuarantor)
                    .update({ is_default: true }, { is_default: false, updated_by: req.auth?.data.name });
            }

            const data = new PatientGuarantor()
            data.guarantor_name = param.guarantor_name;
            data.phone = param.phone;
            // data.province = param.province;
            // data.city = param.city;
            data.administrativu = param.administrativu;
            data.suco = param.suco;
            data.aldeia = param.aldeia;
            data.munisipo = param.munisipo;
            // data.zip_code = param.zip_code;
            data.agreement_no = param.agreement_no;
            data.agreement_desc = param.agreement_desc;
            data.patient_group = param.patient_group_id;
            data.faretype = param.faretype;
            data.is_default = param.is_default;
            data.is_full_paid = param.is_full_paid;
            data.maximal_liability = param.maximalliability;
            data.created_by = req.auth?.data.name;
            data.updated_by = req.auth?.data.name;

            await OrmHelper.DB.manager.save(data);

            return ReturnHelper.successResponseAny(res, 200, Language.lang.success_insert, data);
        } catch (e: unknown) {
            log.error(e);
            const err = e as Error;

            return ReturnHelper.errorResponse(res, 500, 401, Language.lang.failed_insert, err.message);
        }
    }

    static async update(req: Request, res: Response, next: NextFunction): Promise<Response> {
        /*
        #swagger.tags = ['PatientGuarantor']
        #swagger.security = [{
            "bearerAuth": []
        }]
         #swagger.parameters['id'] = {
            in: 'path',
            description: 'PatientGuarantor ID.',
            required: true,
            type: 'string'
        }
    
         #swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                         $ref: "#/components/schemas/patient_guarantor"
                    }  
                }
            }
        }
        */

        try {
            const schema = Joi.object().keys({
                id: Joi.string().uuid().required().label('ID'),
                guarantor_name: Joi.string().max(256).required().label('Guarantor Name'),
                phone: Joi.string().max(15).required().label('Phone'),
                // province: Joi.string().max(128).required().label('Province'),
                // city: Joi.string().max(128).required().label('City'),
                munisipo: Joi.string().allow(null, "").label("Munisipo ID"),
                administrativu: Joi.string().allow(null, "").label("Administrativu ID"),
                aldeia: Joi.string().allow(null, "").label("Aldeia ID"),
                suco: Joi.string().allow(null, "").label("Suco ID"),
                // zip_code: Joi.string().max(10).required().label('Zip Code'),
                agreement_no: Joi.string().max(50).required().label('Agreement No.'),
                agreement_desc: Joi.string().max(512).optional().label('Agreement Description'),
                patient_group_id: Joi.string().guid({ version: 'uuidv4' }).required().label('Patient Group'),
                faretype: Joi.string().guid({ version: 'uuidv4' }).required().label('Fare Type'),
                maximalliability: Joi.number().optional().label('Maximal Liability'),
                is_default: Joi.bool().optional().default(false).label('Is Default'),
                is_full_paid: Joi.bool().optional().default(false).label('Is Full Paid'),
            });

            req.body.id = req.params['id'];

            const param: any = await schema.validateAsync(req.body);

            const repo = OrmHelper.DB.getRepository(PatientGuarantor);

            const data = await repo.findOneBy({ id: param.id });

            if (!data) return ReturnHelper.errorResponse(res, 404, 401, Language.lang.failed_not_found, "");

            if (param.is_default === true) {
                await OrmHelper.DB.getRepository(PatientGuarantor)
                    .update({ is_default: true }, { is_default: false, updated_by: req.auth?.data.name });
            }

            data.guarantor_name = param.guarantor_name;
            data.phone = param.phone;
            // data.province = param.province;
            // data.city = param.city;
            data.administrativu = param.administrativu;
            data.suco = param.suco;
            data.aldeia = param.aldeia;
            data.munisipo = param.munisipo;
            // data.zip_code = param.zip_code;
            data.agreement_no = param.agreement_no;
            data.agreement_desc = param.agreement_desc;
            data.patient_group = param.patient_group_id;
            data.faretype = param.faretype;
            data.maximal_liability = param.maximalliability;
            data.is_default = param.is_default;
            data.is_full_paid = param.is_full_paid;
            data.created_by = req.auth?.data.name;
            data.updated_by = req.auth?.data.name;

            await repo.save(data);

            return ReturnHelper.successResponseAny(res, 200, Language.lang.success_update, data);
        } catch (e: unknown) {
            log.error(e);
            const err = e as Error;

            return ReturnHelper.errorResponse(res, 500, 402, Language.lang.failed_update, err.message);
        }
    }

    static async delete(req: Request, res: Response, next: NextFunction): Promise<Response> {
        /*
        #swagger.tags = ['PatientGuarantor']
        #swagger.security = [{
            "bearerAuth": []
        }]
        #swagger.parameters['id'] = {
            in: 'path',
            description: 'Item Group ID.',
            required: true,
            type: 'string'
        }
        #swagger.parameters['hard'] = {
            in: 'path',
            description: 'Is Hard Delete',
            required: false,
            type: 'boolean'
        }
        */
        try {
            const schema = Joi.object().keys({
                id: Joi.string().uuid().required().label('ID'),
                hard: Joi.bool().optional().allow('').label('Is hard delete?')
            });

            const param: { id: string, hard: boolean } = await schema.validateAsync(req.params);

            const repo = OrmHelper.DB.getRepository(PatientGuarantor);

            const existData = await repo.findOne({ where: { id: param.id } });
            if (existData && !param.hard) {
                existData.deleted_by = req.auth?.data.name;
                await OrmHelper.DB.manager.save(existData);
            }

            const affected = (!param.hard ? await repo.softDelete({ id: param.id }) : await repo.delete({ id: param.id })).affected ?? 0;

            if (affected > 0) {
                return ReturnHelper.successResponseAny(res, 200, Language.lang.success_delete, {});
            } else {
                return ReturnHelper.errorResponse(res, 404, 401, Language.lang.failed_not_found, "");
            }
        } catch (e: unknown) {
            log.error(e);
            const err = e as Error;

            return ReturnHelper.errorResponse(res, 500, 402, Language.lang.failed_delete, err.message);
        }
    }

    static async restore(req: Request, res: Response, next: NextFunction): Promise<Response> {
        /*
        #swagger.tags = ['PatientGuarantor']
        #swagger.security = [{
            "bearerAuth": []
        }]
            
        #swagger.parameters['id'] = {
            in: 'path',
            description: 'PatientGuarantor ID.',
            required: true,
            type: 'string'
        }
        */
        try {
            const schema = Joi.object().keys({
                id: Joi.string().uuid().required().label('ID')
            });

            const param: PatientGuarantor = await schema.validateAsync(req.params);

            const repo = OrmHelper.DB.getRepository(PatientGuarantor);

            const affected = (await repo.restore({ id: param.id })).affected ?? 0;

            if (affected > 0) {
                return ReturnHelper.successResponseAny(res, 200, Language.lang.success_restore, {});
            } else {
                return ReturnHelper.errorResponse(res, 404, 401, Language.lang.failed_not_found, "");
            }
        } catch (e: unknown) {
            log.error(e);
            const err = e as Error;

            return ReturnHelper.errorResponse(res, 500, 402, Language.lang.failed_restore, err.message);
        }
    }

    static async detail(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
        /*
            #swagger.tags = ['PatientGuarantor']
            #swagger.security = [{ "bearerAuth": [] }]
            #swagger.parameters['id'] = { description: '', in: 'path', type: 'string' }
            */
        try {
            const schema = Joi.object().keys({
                id: Joi.string().uuid().required().label("Patient Guarantor Id"),
            });

            let param: any = await schema.validateAsync(req.params);

            let data = await PatientGuarantorModel.list({ "patient_guarantor.id": param.id }).then((q) => q.getOne());
            if (!data) throw { message: "Patient Guarantor Not Found" };

            return ReturnHelper.successResponseAny(res, 200, Language.lang.success_view, data);
        } catch (e: unknown) {
            log.error(e);
            const err = e as Error;
            return ReturnHelper.errorResponse(res, 400, 401, Language.lang.failed_not_found, err.message);
        }
    }
}