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 { Factory, FactoryToSupplier, Paging, Supplier } from "entity";
import CommonHelper from "../../helpers/common";
import * as fastcsv from 'fast-csv';
import dayjs from "dayjs";
import { FactoryToSupplierModel } from "../../model/factory_to_supplier";

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

export class FactorytoSupplierController {
    static async list(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
        /*
            #swagger.tags = ['Pharmacy - FactoryToSupplier']
            #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: any = await schema.validateAsync(req.query);

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

            var query = await FactoryToSupplierModel.list(filter);

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

            const res_count = query;
            const res_list = query
                .orderBy("factory_to_supplier." + 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 = ['Pharmacy - FactoryToSupplier']
        #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: any = await schema.validateAsync(req.query);

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

            var query = await FactoryToSupplierModel.list(filter);
            const data = await query.getMany();
            
            const filename = "factory_to_supplier.csv";

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

            const csvStream = fastcsv.format({
                headers: true,
                writeHeaders: true,
                transform: (row: FactoryToSupplier): 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 = ['Pharmacy - FactoryToSupplier']
        #swagger.security = [{
            "bearerAuth": []
        }]
        
        #swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                         $ref: "#/components/schemas/factory_to_supplier"
                    }  
                }
            }
        }
        */
        try {
            const schema = Joi.object().keys({
                supplier_id: Joi.string()
                .uuid()
                .required()
                .label("Supplier ID"),
        
                factory_ids: Joi.array()
                    .items(Joi.string().uuid().required())
                    .min(1)
                    .required()
                    .label("Factory IDs")
            });

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

            const factoryToSupplierRepo = OrmHelper.DB.getRepository(FactoryToSupplier);
            const factoryRepo = OrmHelper.DB.getRepository(Factory);
            const supplierRepo = OrmHelper.DB.getRepository(Supplier);

            await factoryToSupplierRepo
                .createQueryBuilder()
                .delete()
                .from(FactoryToSupplier)
                .where("supplier_id = :supplierId", { supplierId: param.supplier_id })
                .execute();

            let relation : FactoryToSupplier;
            for (const factoryId of param.factory_ids) {
                relation = new FactoryToSupplier();
                relation.factory = await factoryRepo.findOneBy({ id: factoryId });
                relation.supplier = await supplierRepo.findOneBy({ id: param.supplier_id });
                relation.created_by = req.auth.data.name;

                await factoryToSupplierRepo.save(relation);
            }

            const data = await factoryToSupplierRepo.createQueryBuilder("factory_to_supplier")
            .leftJoinAndSelect("factory_to_supplier.factory", "factory")
            .leftJoinAndSelect("factory_to_supplier.supplier", "supplier")
            .where("factory_to_supplier.supplier_id = :supplierId", { supplierId: param.supplier_id }).getMany();
            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 = ['Pharmacy - FactoryToSupplier']
        #swagger.security = [{
            "bearerAuth": []
        }]
         #swagger.parameters['supplier_id'] = {
            in: 'path',
            description: 'Supplier ID.',
            required: true,
            type: 'string'
        }
    
         #swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                         $ref: "#/components/schemas/factory_to_supplier"
                    }  
                }
            }
        }
        */

        try {
            const schema = Joi.object().keys({
                supplier_id: Joi.string()
                .uuid()
                .required()
                .label("Supplier ID"),
        
                factory_ids: Joi.array()
                    .items(Joi.string().uuid().optional())
                    .required()
                    .label("Factory IDs")
            });

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

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

            const factoryToSupplierRepo = OrmHelper.DB.getRepository(FactoryToSupplier);
            const factoryRepo = OrmHelper.DB.getRepository(Factory);
            const supplierRepo = OrmHelper.DB.getRepository(Supplier);

            const supplier = await supplierRepo.findOneBy({ id: param.supplier_id });
            if(supplier == null) {
                return ReturnHelper.errorResponse(res, 404, 401, Language.lang.failed_not_found, "");
            }

            await factoryToSupplierRepo
                .createQueryBuilder()
                .delete()
                .from(FactoryToSupplier)
                .where("supplier_id = :supplierId", { supplierId: param.supplier_id })
                .execute();

            if(param.factory_ids.length > 0) {
                let relation : FactoryToSupplier;
                for (const factoryId of param.factory_ids) {
                    relation = new FactoryToSupplier();
                    relation.factory = await factoryRepo.findOneBy({ id: factoryId });
                    relation.supplier = await supplierRepo.findOneBy({ id: param.supplier_id });
                    relation.created_by = req.auth.data.name;

                    await factoryToSupplierRepo.save(relation);
                }
            }
            
            const data = await factoryToSupplierRepo.createQueryBuilder("factory_to_supplier")
            .leftJoinAndSelect("factory_to_supplier.factory", "factory")
            .leftJoinAndSelect("factory_to_supplier.supplier", "supplier")
            .where("factory_to_supplier.supplier_id = :supplierId", { supplierId: param.supplier_id }).getMany();
            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 = ['Pharmacy - FactoryToSupplier']
        #swagger.security = [{
            "bearerAuth": []
        }]
        
        #swagger.parameters['supplier_id'] = {
            in: 'path',
            description: 'Supplier ID.',
            required: true,
            type: 'string'
        }
        #swagger.parameters['hard'] = {
            in: 'path',
            description: 'Is Hard Delete',
            required: true,
            type: 'boolean'
        }
       
        */
        try {
            const schema = Joi.object().keys({
                supplier_id: Joi.string().uuid().required().label('Supplier ID'),
                hard: Joi.bool().optional().allow('').label('Is hard delete?')
            });

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

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

            let baseQuery = repo.createQueryBuilder().where("supplier_id = :supplierId", { supplierId: param.supplier_id });

            const count = await baseQuery.getCount();
            if (count === 0) return ReturnHelper.errorResponse(res, 404, 401, Language.lang.failed_not_found, "");
            
            if (!param.hard) {
                let updateQuery = repo.createQueryBuilder().update(FactoryToSupplier)
                    .set({ deleted_by: req.auth.data.name })
                    .where("supplier_id = :supplierId", {supplierId: param.supplier_id});
    
                await updateQuery.execute();
    
                let softDeleteQuery = repo.createQueryBuilder().softDelete()
                    .where("supplier_id = :supplierId", {supplierId: param.supplier_id});
    
                await softDeleteQuery.execute();
            } else {
                let deleteQuery = repo.createQueryBuilder().delete()
                    .where("supplier_id = :supplierId", {supplierId: param.supplier_id});
    
                await deleteQuery.execute();
            }

            return ReturnHelper.successResponseAny(res, 200, Language.lang.success_delete, {});
        } 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 = ['Pharmacy - FactoryToSupplier']
        #swagger.security = [{
            "bearerAuth": []
        }]
            
        #swagger.parameters['supplier_id'] = {
            in: 'path',
            description: 'Supplier ID.',
            required: false,
            type: 'string'
        }
        */
        try {
            const schema = Joi.object().keys({
                supplier_id: Joi.string().uuid().required().label('Supplier ID'),
            });

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

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

            let restoreQuery = repo.createQueryBuilder().restore()
                    .where("supplier_id = :supplierId", {supplierId: param.supplier_id});

            const affected = (await restoreQuery.execute()).affected;

            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);
        }
    }
}