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 { UserToRoom, Paging, User, Room } from "entity";
import CommonHelper from "../helpers/common";
import * as fastcsv from 'fast-csv';
import dayjs from "dayjs";
import { UserToRoomModel } from "../model/user_to_room";
import { RoomModel } from "../model/room";

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

export class UserToRoomController {
    static async list(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
        /*
            #swagger.tags = ['UserToRoom']
            #swagger.security = [{ "bearerAuth": [] }]
            #swagger.parameters['filter'] = { 
                description: "Filter in JSON format. Available fields: user_id (string, uuid, exact match), name (string, partial match case-insensitive), status (string, exact match). Example: {\"user_id\":\"uuid-here\",\"name\":\"john\",\"status\":\"active\"}", 
                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;

            // Base filter builder (reusable untuk step 1 & count)
            const applyFilters = (qb: any) => {
                if (param.with_deleted) qb.withDeleted();
                const userIdFilter = filter["user.id"] ?? filter.user_id ?? filter.doctor_id ?? filter.id;
                if (userIdFilter !== undefined && userIdFilter !== "") {
                    qb.andWhere("user.id = :userId", { userId: userIdFilter });
                }

                const userNameFilter = filter["user.name"] ?? filter.name;
                if (userNameFilter !== undefined && userNameFilter !== "") {
                    const userNameVal = String(userNameFilter);
                    qb.andWhere("user.name ILIKE :name", { name: userNameVal.includes("%") ? userNameVal : `%${userNameVal}%` });
                }

                const userStatusFilter = filter["user.status"] ?? filter.status;
                if (userStatusFilter !== undefined && userStatusFilter !== "") qb.andWhere("user.status = :status", { status: userStatusFilter });
                return qb;
            };

            // Step 1: Ambil paginated user IDs dulu (tanpa join room)
            const idQuery = OrmHelper.DB.getRepository(User)
                .createQueryBuilder("user")
                .select("user.id")
                .orderBy("user." + param.order_field, param.order_direction as "ASC" | "DESC")
                .offset(offset)
                .limit(limit);

            applyFilters(idQuery);

            const paginatedUserIds = await idQuery.getRawMany();
            const userIds = paginatedUserIds.map((row) => row.user_id);

            if (userIds.length === 0) {
                return ReturnHelper.successResponselist(
                    res,
                    200,
                    Language.lang.success_view,
                    0,
                    param.page,
                    0,
                    []
                );
            }

            // Step 2: Count total (tanpa join room, tanpa offset/limit)
            const countQuery = OrmHelper.DB.getRepository(User)
                .createQueryBuilder("user")
                .select("user.id");

            applyFilters(countQuery);

            const total_count_data = await countQuery.getCount();

            // Step 3: Fetch data lengkap hanya untuk IDs yang sudah dipaginasi
            const userQuery = OrmHelper.DB.getRepository(User)
                .createQueryBuilder("user")
                .leftJoinAndSelect("user.roles", "roles")
                .leftJoinAndMapMany(
                    "user.userToRooms",
                    UserToRoom,
                    "user_to_room",
                    "user_to_room.user = user.id"
                )
                .leftJoinAndMapOne(
                    "user_to_room.roomData",
                    Room,
                    "room",
                    "room.id = user_to_room.room"
                )
                .whereInIds(userIds)
                .orderBy("user." + param.order_field, param.order_direction as "ASC" | "DESC");

            if (param.with_deleted) userQuery.withDeleted();

            const users = await userQuery.getMany();

            // Transform data
            const list_data_return = users.map((user: any) => {
                const userToRooms: any[] = user.userToRooms ?? [];

                const rooms: Record<string, any> = {};
                userToRooms.forEach((utr: any, index: number) => {
                    const room = utr.roomData ?? null;
                    rooms[`room_${index + 1}`] = room ? {
                        id: room.id,
                        room: room.room,
                        code: room.code,
                    } : null;
                });

                return {
                    id: user.id,
                    name: user.name,
                    username: user.username,
                    email: user.email,
                    status: user.status,
                    roles: user.roles ? user.roles.map((role: any) => ({
                        id: role.id,
                        name: role.name,
                    })) : [],
                    rooms: Object.keys(rooms).length > 0 ? rooms : 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 = ['UserToRoom']
        #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 UserToRoomModel.list(filter);
            const data = await query.getMany();

            const filename = "user_to_room.csv";

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

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

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

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

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

            // const userToRoomRepo = OrmHelper.DB.getRepository(UserToRoom);
            // const userRepo = OrmHelper.DB.getRepository(User);
            // const roomRepo = OrmHelper.DB.getRepository(Room);

            // await userToRoomRepo
            //     .createQueryBuilder()
            //     .delete()
            //     .from(UserToRoom)
            //     .where("service_id = :userId", { userId: param.user_id })
            //     .execute();

            const data = new UserToRoom()
            data.user = param.user_id;
            data.room = param.room_id;
            data.created_by = req.auth?.data.name;

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

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

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

            // const data = await userToRoomRepo.createQueryBuilder("user_to_room")
            // .leftJoinAndSelect("user_to_room.user", "user")
            // .leftJoinAndSelect("user_to_room.room", "room")
            // .where("user_to_room.service_id = :userId", { userId: param.user_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 = ['UserToRoom']
        #swagger.security = [{
            "bearerAuth": []
        }]
         #swagger.parameters['user_id'] = {
            in: 'path',
            description: 'User ID.',
            required: true,
            type: 'string'
        }
    
         #swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                         $ref: "#/components/schemas/user_to_room_update"
                    }  
                }
            }
        }
        */

        try {
            const schema = Joi.object().keys({
                user_id: Joi.string().uuid().required().label('User ID'),
                room_ids: Joi.array()
                    .items(Joi.string().uuid().required())
                    .min(1)
                    .required()
                    .label("Factory IDs")
                // room_id: Joi.string().uuid().required().label('Room ID'),
            });

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

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

            const userToRoomRepo = OrmHelper.DB.getRepository(UserToRoom);
            const userRepo = OrmHelper.DB.getRepository(User);
            const roomRepo = OrmHelper.DB.getRepository(Room);

            await userToRoomRepo
                .createQueryBuilder()
                .delete()
                .from(UserToRoom)
                .where("user = :userId", { userId: param.user_id })
                .execute();

            let relation: UserToRoom | any;
            for (const roomId of param.room_ids) {
                relation = new UserToRoom();
                relation.user = await userRepo.findOneBy({ id: param.user_id });
                relation.room = await roomRepo.findOneBy({ id: roomId });
                relation.created_by = req.auth?.data.name;

                await userToRoomRepo.save(relation);
            }

            const data = await userToRoomRepo.createQueryBuilder("user_to_room")
                .leftJoinAndSelect("user_to_room.user", "user")
                .leftJoinAndSelect("user_to_room.room", "room")
                .where("user_to_room.user = :userId", { userId: param.user_id }).getMany();

            return ReturnHelper.successResponseAny(res, 200, Language.lang.success_update, data);

            // const repo = OrmHelper.DB.getRepository(UserToRoom);

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

            // if (data != null) {
            //     data.user = param.user_id;
            //     data.room = param.room_id;
            //     data.updated_by = req.auth.data.name;

            //     await repo.save(data);

            //     return ReturnHelper.successResponseAny(res, 200, Language.lang.success_update, data);
            // } 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_update, err.message);
        }
    }

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

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

            let data = await UserToRoomModel.list({ "id": param.id }).then((q) => q.getOne());
            if (!data) throw { message: "UserToRoom 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);
        }
    }

    static async listRoom(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
        /*
            #swagger.tags = ['UserToRoom']
            #swagger.security = [{ "bearerAuth": [] }]
            #swagger.parameters['filter'] = { description: 'Filter in JSON format. Available fields: user_id (string, uuid, exact match), name (string, partial match case-insensitive), status (string, exact match). Example: {\"user_id\":\"uuid-here\",\"name\":\"john\",\"status\":\"active\"}', 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 query = await RoomModel.list(filter);

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

            const res_count = query;
            const res_list = query
                .leftJoinAndSelect("Room.department", "department")
                .orderBy("Room." + param.order_field, param.order_direction as "ASC" | "DESC")
                .take(limit)
                .skip(offset);

            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_not_found, err.message);
        }
    }

    static async listRoomByUser(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
        /*
            #swagger.tags = ['UserToRoom']
            #swagger.security = [{ "bearerAuth": [] }]
            #swagger.parameters['user_id'] = { description: 'User ID.', in: 'path', type: 'string' }
            #swagger.parameters['filter'] = { description: 'Filter in JSON format. Available fields: user_id (string, uuid, exact match), name (string, partial match case-insensitive), status (string, exact match). Example: {\"user_id\":\"uuid-here\",\"name\":\"john\",\"status\":\"active\"}', 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 paramPathSchema = Joi.object().keys({
                user_id: Joi.string().uuid().required().label("User ID"),
            });

            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 paramPath = await paramPathSchema.validateAsync(req.params);
            let param: Paging = await schema.validateAsync(req.query);
            let filter = param.filter && param.filter !== "" ? JSON.parse(param.filter) : {};

            const query = await RoomModel.list(filter);

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

            query.innerJoin(UserToRoom, "user_to_room", "user_to_room.room = Room.id")
                .andWhere("user_to_room.user = :userId", { userId: paramPath.user_id });

            const res_count = query;
            const res_list = query
                .leftJoinAndSelect("Room.department", "department")
                .orderBy("Room." + param.order_field, param.order_direction as "ASC" | "DESC")
                .take(limit)
                .skip(offset);

            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_not_found, err.message);
        }
    }
}