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 { RoomToPharmacy, Paging, Room } from "entity";
import CommonHelper from "../helpers/common";
import * as fastcsv from 'fast-csv';
import dayjs from "dayjs";
import { RoomToPharmacyModel } from "../model/room_to_pharmacy";

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

export class RoomToPharmacyController {
    // static async list(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
    //     /*
    //         #swagger.tags = ['RoomToPharmacy']
    //         #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"),
    //         });
    //         const param: Paging = await schema.validateAsync(req.query);

    //         const filter = param.filter && param.filter !== "" ? JSON.parse(param.filter) : {};
    //         const filterAny = filter.any && filter.any !== "" ? filter.any : "";
    //         let filterObj = { ...filter } as any;
    //         delete filterObj.any;

    //         const query = await RoomToPharmacyModel.list(filterObj);
    //         const offset = (param.page - 1) * param.limit;

    //         const res_count = query;
    //         const res_list = query
    //             .leftJoinAndSelect("room_to_pharmacy.pharmacy_room", "emrregistration")
    //             .leftJoinAndSelect("room_to_pharmacy.room", "room")
    //             .orderBy("room_to_pharmacy." + param.order_field, param.order_direction)
    //             .offset(offset)
    //             .limit(param.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 list(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
        /*
            #swagger.tags = ['RoomToPharmacy']
            #swagger.security = [{ "bearerAuth": [] }]
           #swagger.parameters['filter'] = { 
                description: "Filter in JSON format. Available fields: room (string, partial match case-insensitive), code (string, partial match case-insensitive), status (string, exact match), pharmacy_room (string, partial match case-insensitive). Example: {\"room\":\"igd\",\"code\":\"R01\",\"status\":\"active\",\"pharmacy_room\":\"apotek\"}", 
                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) : {};

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

            const roomQuery = OrmHelper.DB.getRepository(Room)
                .createQueryBuilder("room")
                .leftJoinAndSelect("room.department", "department")
                .leftJoinAndMapMany(
                    "room.roomToPharmacies",
                    RoomToPharmacy,
                    "room_to_pharmacy",
                    "room_to_pharmacy.room_id = room.id"
                )
                .leftJoinAndMapOne(
                    "room_to_pharmacy.pharmacy_room",
                    Room,
                    "pharmacy_room",
                    "pharmacy_room.id = room_to_pharmacy.pharmacy_room_id"
                )
                .where("department.id IN (:...departmentIds)", {
                    departmentIds: [
                        '42bc42a7-e2a7-4f95-a788-9d9e51a51a20',
                        '3fc39ff1-b4bc-4276-92ef-def7ca9432fb',
                        'a0d2ef11-6927-4e5c-8628-6acf26351071',
                    ]
                })
                .orderBy("room." + param.order_field, param.order_direction as "ASC" | "DESC");

            if (param.with_deleted) {
                roomQuery.withDeleted();
            }

            // Filter tambahan jika ada
            const roomNameFilter = filter["room.name"] ?? filter.room;
            if (roomNameFilter !== undefined && roomNameFilter !== "") {
                const roomVal = String(roomNameFilter);
                roomQuery.andWhere("room.room ILIKE :room", { room: roomVal.includes("%") ? roomVal : `%${roomVal}%` });
            }
            if (filter.status) {
                roomQuery.andWhere("room.status = :status", { status: filter.status });
            }

            // Filter room.code
            if (filter.code && filter.code !== "") {
                roomQuery.andWhere("room.code ILIKE :code", { code: `%${filter.code}%` });
            }

            // Filter pharmacy_room.room
            if (filter.pharmacy_room && filter.pharmacy_room !== "") {
                roomQuery.andWhere("pharmacy_room.room ILIKE :pharmacy_room", { pharmacy_room: `%${filter.pharmacy_room}%` });
            }

            const total_count_data = await roomQuery.clone().getCount();

            const rooms = await roomQuery
                .offset(offset)
                .limit(limit)
                .getMany();

            // Transform: { room_name: { pharmacy_room_1: {}, pharmacy_room_2: {} } }
            const list_data_return = rooms.map((room: any) => {
                const roomToPharmacies: any[] = room.roomToPharmacies ?? [];

                const pharmacyRooms: Record<string, any> = {};
                roomToPharmacies.forEach((rtp: any, index: number) => {
                    const pharmacy: Room | null = rtp.pharmacy_room ?? null;
                    pharmacyRooms[`pharmacy_room_${index + 1}`] = pharmacy ? {
                        id: pharmacy.id,
                        room: pharmacy.room,
                        code: pharmacy.code,
                        description: pharmacy.description ?? null,
                        status: pharmacy.status,
                    } : null;
                });

                return {
                    rooms: {
                        id: room.id,
                        room: room.room,
                        code: room.code,
                        description: room.description ?? null,
                        status: room.status,
                        department: room.department ? {
                            id: room.department.id,
                            name: room.department.name,
                        } : null,
                        pharmacy_rooms: Object.keys(pharmacyRooms).length > 0
                            ? pharmacyRooms
                            : null,
                    }
                };
            });

            const count_data = CommonHelper.countObject(list_data_return);

            return ReturnHelper.successResponselist(
                res,
                200,
                Language.lang.success_view,
                count_data,
                param.page,
                total_count_data,
                list_data_return
            );
        } 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 = ['RoomToPharmacy']
        #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 RoomToPharmacyModel.list(filter);
            const data = await query.getMany();

            const filename = "room_to_pharmacy.csv";

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

            const csvStream = fastcsv.format({
                headers: true,
                writeHeaders: true,
                transform: (row: RoomToPharmacy): 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 = ['RoomToPharmacy']
        #swagger.security = [{
            "bearerAuth": []
        }]
        
        #swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                         $ref: "#/components/schemas/room_to_pharmacy"
                    }  
                }
            }
        }
        */
        try {
            const schema = Joi.object().keys({
                pharmacy_room_id: Joi.string()
                    .uuid()
                    .required()
                    .label("Pharmacy Room ID"),

                room_id: Joi.string()
                    .uuid()
                    .required()
                    .label("Room ID"),

                // room_ids: Joi.array()
                //     .items(Joi.string().uuid().required())
                //     .min(1)
                //     .required()
                //     .label("Room IDs")
            });

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

            const data = new RoomToPharmacy()
            data.pharmacy_room = param.pharmacy_room_id;
            data.room = param.room_id;
            data.created_by = req.auth?.data.name;

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

            // await RoomToPharmacyRepo
            //     .createQueryBuilder()
            //     .delete()
            //     .from(RoomToPharmacy)
            //     .where("pharmacy_room_id = :pharmacyRoomId", { pharmacyRoomId: param.pharmacy_room_id })
            //     .execute();

            // let relation : RoomToPharmacy;
            // for (const roomId of param.room_ids) {
            //     relation = new RoomToPharmacy();
            //     relation.room = await roomRepo.findOneBy({ id: roomId });
            //     relation.pharmacy_room = await roomRepo.findOneBy({ id: param.pharmacy_room_id });
            //     relation.created_by = req.auth.data.name;

            //     await RoomToPharmacyRepo.save(relation);
            // }

            // const data = await RoomToPharmacyRepo.createQueryBuilder("room_to_pharmacy")
            // .leftJoinAndSelect("room_to_pharmacy.room", "room")
            // .leftJoinAndSelect("room_to_pharmacy.pharmacy_room", "pharmacy_room")
            // .where("room_to_pharmacy.pharmacy_room_id = :pharmacyRoomId", { pharmacyRoomId: param.pharmacy_room_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 = ['RoomToPharmacy']
        #swagger.security = [{
            "bearerAuth": []
        }]
    
        #swagger.parameters['room_id'] = {
            in: 'path',
            description: 'Room ID.',
            required: true,
            type: 'string'
        }
        
        #swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                            $ref: "#/components/schemas/room_to_pharmacy"
                    }  
                }
            }
        }
        */
        try {
            const schema = Joi.object().keys({
                room_id: Joi.string().uuid().required(),
                pharmacy_room_id: Joi.string().uuid().required(),
            });

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

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

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

            // ✅ cari berdasarkan room saja
            let data = await repo.findOne({
                where: {
                    room: { id: param.room_id }
                },
                relations: ["room", "pharmacy_room"]
            });

            // ambil pharmacy room
            const pharmacyRoom = await OrmHelper.DB.getRepository(Room).findOneBy({
                id: param.pharmacy_room_id
            });

            if (!pharmacyRoom) {
                throw new Error("Pharmacy Room not found");
            }

            if (data) {
                data.pharmacy_room = pharmacyRoom;
                data.updated_by = req.auth?.data.name;

                await repo.save(data);
            } else {
                const room = await OrmHelper.DB.getRepository(Room).findOneBy({
                    id: param.room_id
                });

                if (!room) throw new Error("Room not found");

                data = new RoomToPharmacy();
                data.room = room;
                data.pharmacy_room = pharmacyRoom;
                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,
                401,
                Language.lang.failed_update,
                err.message
            );
        }
    }

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

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

            let data = await OrmHelper.DB.getRepository(Room)
                .createQueryBuilder("room")
                .leftJoinAndSelect("room.department", "department")
                .leftJoinAndMapMany(
                    "room.roomToPharmacies",
                    RoomToPharmacy,
                    "room_to_pharmacy",
                    "room_to_pharmacy.room_id = room.id"
                )
                .leftJoinAndMapOne(
                    "room_to_pharmacy.pharmacy_room",
                    Room,
                    "pharmacy_room",
                    "pharmacy_room.id = room_to_pharmacy.pharmacy_room_id"
                )
                .where("room.id = :id", { id: param.id })
                .getOne();

            if (!data) throw { message: "RoomToPharmacy 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);
        }
    }
}