import { QueueMonitoring, Paging, QueueMonitoringRooms, Status } from "entity";
import { NextFunction, Response } from "express";
import { Request } from "express-jwt";
import Joi from "joi";
import { ILogObj, Logger } from "tslog";
import CommonHelper from "../helpers/common";
import { ReturnHelper } from "../helpers/express/return";
import { Language } from "../langs/lang";
import { QueueMonitoringModel } from "../model/queue_monitoring";
import { RoomModel } from "../model/room";
import { OrmHelper } from "../helpers/orm";
import moment from "moment";

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

export class QueueMonitoringController {
	static async list(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
		/*
			#swagger.tags = ['Queue Monitoring']
			#swagger.security = [{ "bearerAuth": [] }]
			#swagger.parameters['filter'] = { description: 'Filter: plain text or JSON object (status, slug, etc.)', 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) : {};

			var query = await QueueMonitoringModel.list(filter);

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

			const res_count = query;
			const res_list = query
				.leftJoinAndMapMany(
					"QueueMonitoring.queue_monitoring_rooms", //
					QueueMonitoringRooms,
					"qmr",
					'qmr."queueMonitoringId" = "QueueMonitoring"."id"',
				)
				.leftJoinAndSelect("qmr.room", "room")
				.leftJoinAndSelect("room.department", "department")
				.orderBy("QueueMonitoring." + 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();
			let list_data = await res_list.getMany();
			const count_data = CommonHelper.countObject(list_data);

			if (list_data && list_data.length > 0) {
				list_data = list_data.map((item) => {
					return {
						...item,
						rooms: (item.queue_monitoring_rooms || []).map((qmr) => qmr.room),
					};
				});

				list_data = list_data.map(({ queue_monitoring_rooms, ...rest }) => rest);
			}

			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 detailBySlug(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
		/*
		 #swagger.tags = ['Queue Monitoring']
		 #swagger.security = [{ "bearerAuth": [] }]
		 #swagger.parameters['slug'] = { in: 'path', type: 'string' }
		*/
		try {
			const schema = Joi.object().keys({
				slug: Joi.string().required().label("Queue Monitoring Slug"),
			});

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

			const queueMonitoring = await QueueMonitoringModel.list({ "QueueMonitoring.slug": param.slug }).then((q) =>
				q //
					.leftJoinAndMapMany(
						"QueueMonitoring.queue_monitoring_rooms", //
						QueueMonitoringRooms,
						"qmr",
						'qmr."queueMonitoringId" = "QueueMonitoring"."id"',
					)
					.leftJoinAndSelect("qmr.room", "room")
					.leftJoinAndSelect("room.department", "department")
					.getOne(),
			);

			if (!queueMonitoring) throw { message: "Queue Monitoring Not Found" };

			if (queueMonitoring) {
				queueMonitoring.rooms = (queueMonitoring.queue_monitoring_rooms || []).map((item) => item.room);

				delete queueMonitoring.queue_monitoring_rooms;
			}

			if (queueMonitoring.rooms && queueMonitoring.rooms.length > 0) {
				try {
					const roomIds = queueMonitoring.rooms.map((room: any) => room.id);
					const today = moment().format("YYYY-MM-DD");

					const placeholders = roomIds.map((_: any, index: number) => `$${index + 1}`).join(", ");
					const dateParamIndex = roomIds.length + 1;
					const queryParams = [...roomIds, today];

					const queueQuery = `
						SELECT 
							ro.id,
							ro.qeue_number,
							ro.registration_status,
							ro."roomId",
							ro.updated_at,
							p.full_name AS fullname_patient
						FROM emr.emr_registration_outpatient ro
						LEFT JOIN emr.emr_registrations r ON ro."registrationId" = r.id
						LEFT JOIN emr.emr_patients p ON r."patientId" = p.id
						WHERE ro."roomId" IN (${placeholders})
						AND DATE(ro.visit_date) = $${dateParamIndex}
						AND ro.registration_status IN ('ON GOING', 'REGISTERED')
						ORDER BY ro."roomId", 
							CASE WHEN ro.registration_status = 'ON GOING' THEN 0 
								 WHEN ro.registration_status = 'REGISTERED' THEN 1 
								 ELSE 2 END,
							ro.qeue_number ASC
					`;

					const allQueues = await OrmHelper.DB.manager.query(queueQuery, queryParams);

					const queuesByRoom: { [key: string]: any[] } = {};
					allQueues.forEach((queue: any) => {
						const roomId = queue.roomId;
						if (roomId) {
							if (!queuesByRoom[roomId]) {
								queuesByRoom[roomId] = [];
							}
							queuesByRoom[roomId].push({
								id: queue.id,
								qeue_number: queue.qeue_number,
								registration_status: queue.registration_status,
								fullname_patient: queue.fullname_patient,
							});
						}
					});

					// room lookup
					const roomIdToRoomObj: { [key: string]: any } = {};
					queueMonitoring.rooms.forEach((room: any) => {
						roomIdToRoomObj[room.id] = room;
					});

					queueMonitoring.rooms = queueMonitoring.rooms.map((room: any) => ({
						...room,
						queues: queuesByRoom[room.id] || [],
					}));

					const latestOnGoing = allQueues
						.filter((q: any) => q.registration_status === "ON GOING")
						.reduce((latest: any, current: any) => {
							const latestDate = new Date(latest?.updated_at || latest?.updatedAt || 0);
							const currentDate = new Date(current?.updated_at || current?.updatedAt || 0);
							return currentDate > latestDate ? current : latest;
						}, undefined);

					(queueMonitoring as any).currentQueue = latestOnGoing
						? {
							room: roomIdToRoomObj[latestOnGoing.roomId]?.room || null,
							id: latestOnGoing.id,
							qeue_number: latestOnGoing.qeue_number,
							registration_status: latestOnGoing.registration_status,
							fullname_patient: latestOnGoing.fullname_patient,
						}
						: null;
				} catch (queryError: any) {
					log.warn(`Failed to fetch queue data from emr.emr_registration_outpatient: ${queryError.message}`);
					queueMonitoring.rooms = queueMonitoring.rooms.map((room: any) => ({
						...room,
						queues: [],
					}));
					(queueMonitoring as any).currentQueue = null;
				}
			}

			const responseData = {
				...queueMonitoring,
			};

			return ReturnHelper.successResponseAny(res, 200, Language.lang.success_view, responseData);
		} 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 create(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
		/*
		 #swagger.tags = ['Queue Monitoring']
		 #swagger.security = [{ "bearerAuth": [] }]
		 #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/queueMonitoring" } } } }
		 */
		const queryRunner = OrmHelper.DB.createQueryRunner();
		await queryRunner.startTransaction();
		try {
			const schema = Joi.object().keys({
				slug: Joi.string().required().label("Slug"),
				name: Joi.string().required().label("Name"),
				room_ids: Joi.array().items(Joi.string().uuid()).min(1).required().label("Room IDs"),
				status: Joi.string().required().label("Status"),
			});

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

			let queueMonitoring = new QueueMonitoring();
			queueMonitoring.slug = param.slug;
			queueMonitoring.name = param.name;
			queueMonitoring.status = param.status;
			queueMonitoring.created_by = req.auth?.data.name;
			queueMonitoring.updated_by = req.auth?.data.name;
			await queryRunner.manager.save(queueMonitoring);

			if (param.room_ids && param.room_ids.length > 0) {
				await queryRunner.manager.getRepository(QueueMonitoringRooms)
					.createQueryBuilder()
					.delete()
					.from(QueueMonitoringRooms)
					.where('"id" = :id', { id: queueMonitoring.id })
					.execute();

				for (const roomId of param.room_ids) {
					const room = await RoomModel.list({ id: roomId }).then((q) => q.getOne());
					if (!room) throw { message: `Room with id ${roomId} not found` };

					let queueMonitoringRooms = new QueueMonitoringRooms();
					queueMonitoringRooms.queue_monitoring = queueMonitoring;
					queueMonitoringRooms.room = room;
					queueMonitoringRooms.status = param.status;
					queueMonitoringRooms.created_by = req.auth?.data.name;
					queueMonitoringRooms.updated_by = req.auth?.data.name;
					await queryRunner.manager.save(queueMonitoringRooms);
				}
			}

			await queryRunner.commitTransaction();

			return ReturnHelper.successResponseAny(res, 200, Language.lang.success_insert, queueMonitoring);
		} catch (e: unknown) {
			await queryRunner.rollbackTransaction();
			log.error(e);
			const err = e as Error;
			return ReturnHelper.errorResponse(res, 400, 401, Language.lang.failed_view, err.message);
		} finally {
			await queryRunner.release();
		}
	}

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

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

			let queueMonitoring = await QueueMonitoringModel.list({ "QueueMonitoring.id": param.id }).then((q) =>
				q //
					.leftJoinAndMapMany(
						"QueueMonitoring.queue_monitoring_rooms", //
						QueueMonitoringRooms,
						"qmr",
						'qmr."queueMonitoringId" = "QueueMonitoring"."id"',
					)
					.leftJoinAndSelect("qmr.room", "room")
					.leftJoinAndSelect("room.department", "department")
					.getOne(),
			);

			if (!queueMonitoring) throw { message: "Queue Monitoring Not Found" };

			if (queueMonitoring) {
				queueMonitoring.rooms = (queueMonitoring.queue_monitoring_rooms || []).map((item) => item.room);

				delete queueMonitoring.queue_monitoring_rooms;
			}

			return ReturnHelper.successResponseAny(res, 200, Language.lang.success_view, queueMonitoring);
		} 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 update(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
		/*
		 #swagger.tags = ['Queue Monitoring']
		 #swagger.security = [{ "bearerAuth": [] }]
		 #swagger.parameters['id'] = { in: 'path', type: 'string' }
		 #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/queueMonitoring" } } } }
		 */
		const queryRunner = OrmHelper.DB.createQueryRunner();
		await queryRunner.startTransaction();

		try {
			req.body.id = req.params["id"];

			const schema = Joi.object().keys({
				id: Joi.string().uuid().required().label("Queue Monitoring ID"),
				slug: Joi.string().required().label("Slug"),
				name: Joi.string().required().label("Name"),
				room_ids: Joi.array().items(Joi.string().uuid()).min(1).required().label("Room IDs"),
				status: Joi.string().required().label("Status"),
			});

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

			let queueMonitoring = await QueueMonitoringModel.list({ "QueueMonitoring.id": param.id }).then((q) => q.getOne());

			if (!queueMonitoring) throw { message: "Queue Monitoring " + Language.lang.failed_not_found };

			queueMonitoring.slug = param.slug;
			queueMonitoring.name = param.name;
			queueMonitoring.status = param.status;
			queueMonitoring.updated_by = req.auth.data.name;
			await queryRunner.manager.save(queueMonitoring);

			if (param.room_ids && param.room_ids.length > 0) {
				await queryRunner.manager //
					.getRepository(QueueMonitoringRooms)
					.createQueryBuilder()
					.delete()
					.from(QueueMonitoringRooms)
					.where('"queueMonitoringId" = :id', { id: queueMonitoring.id })
					.execute();

				for (const roomId of param.room_ids) {
					const room = await RoomModel.list({ id: roomId }).then((q) => q.getOne());
					if (!room) throw { message: `Room with id ${roomId} not found` };

					let queueMonitoringRooms = new QueueMonitoringRooms();
					queueMonitoringRooms.queue_monitoring = queueMonitoring;
					queueMonitoringRooms.room = room;
					queueMonitoringRooms.status = param.status;
					queueMonitoringRooms.created_by = req.auth.data.name;
					queueMonitoringRooms.updated_by = req.auth.data.name;
					await queryRunner.manager.save(queueMonitoringRooms);
				}
			}

			await queryRunner.commitTransaction();

			return ReturnHelper.successResponseAny(res, 200, Language.lang.success_update, queueMonitoring);
		} catch (e: unknown) {
			await queryRunner.rollbackTransaction();
			log.error(e);
			const err = e as Error;
			return ReturnHelper.errorResponse(res, 400, 401, Language.lang.failed_view, err.message);
		} finally {
			await queryRunner.release();
		}
	}

	static async delete(req: Request, res: Response, next: NextFunction): Promise<Response> {
		/*
		#swagger.tags = ['Queue Monitoring']
		#swagger.security = [{ "bearerAuth": [] }]
		#swagger.parameters['id'] = { in: 'path', 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);

			let affected = 0;
			if (!param.hard) {
				let queueMonitoring: QueueMonitoring = await QueueMonitoringModel.list({ "QueueMonitoring.id": param.id }).then((q) => q.getOne());

				if (!queueMonitoring) throw { message: "Queue Monitoring " + Language.lang.failed_not_found };

				queueMonitoring.deleted_by = req.auth.data.name;
				queueMonitoring.deleted_at = moment().toDate();
				await OrmHelper.DB.manager.save(queueMonitoring);
				affected = 1;
			} else {
				const repo = OrmHelper.DB.getRepository(QueueMonitoring);
				affected = (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 = ['Queue Monitoring']
		#swagger.security = [{ "bearerAuth": [] }]
		#swagger.parameters['id'] = { in: 'path', required: true, type: 'string' }
		*/
		try {
			const schema = Joi.object().keys({
				id: Joi.string().uuid().required().label("ID"),
			});

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

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

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