import { Paging, InpatientRoom, Room, InpatientRoomBed, InpatientRoomBedStatus } 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 { OrmHelper } from "../helpers/orm";
import { Language } from "../langs/lang";
import { InpatientRoomModel } from "../model/inpatient_room";
import { RoomModel } from "../model/room";

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

export class InpatientRoomController {
	static async list(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
		/*
    #swagger.tags = ['Inpatient Room']
    #swagger.security = [{
      "bearerAuth": []
    }]    
    #swagger.parameters['filter'] = {
      descriptionk:'',
      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 offset = (param.page - 1) * param.limit;
			const filter = JSON.parse(param.filter);
			const query = await InpatientRoomModel.list(filter);
			const limit = param.limit;

			const res_count = query;
			const res_list = query
				.leftJoinAndSelect("InpatientRoom.room", "room")
				.leftJoinAndSelect("room.serviceclass", "service_class")
				.orderBy("InpatientRoom." + 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 create(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
		/*
          #swagger.tags = ['Inpatient Room']
          #swagger.security = [{
            "bearerAuth": []
          }]
          #swagger.requestBody = {
            required: true,
            content: {
              "application/json": {
                schema: {
                  $ref: "#/components/schemas/inpatient_room"
                }  
              }
            }
          }
        */

		const queryRunner = OrmHelper.DB.createQueryRunner();
		await queryRunner.startTransaction();

		try {
			const schema = Joi.object().keys({
				room_id: Joi.string().uuid().required().label("Room ID"),
				name: Joi.string().required().label("Name"),
				number_of_bed: Joi.number().required().min(0).label("Number of Bed"),
			});

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

			let room: Room = await RoomModel.list({ id: param.room_id }).then((q) => q.getOne());
			if (!room) throw { message: "Room " + Language.lang.failed_not_found };

			const data = new InpatientRoom();
			data.room = room;
			data.name = param.name;
			data.number_of_bed = param.number_of_bed;
			data.created_by = req.auth?.data.name;

			await queryRunner.manager.save(data);

			for (let i = 1; i <= param.number_of_bed; i++) {
				const bed = new InpatientRoomBed();
				bed.inpatient_room = data;
				bed.number = i;
				bed.status = InpatientRoomBedStatus.Empty;
				bed.created_by = req.auth?.data.name;
				await queryRunner.manager.save(bed);
			}

			await queryRunner.commitTransaction();

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

	static async detail(req: Request, res: Response, next: NextFunction): Promise<Response> {
		/*
        #swagger.tags = ['Inpatient Room']
        #swagger.security = [{
            "bearerAuth": []
        }]
        #swagger.parameters['id'] = {
            in: 'path',
            description: 'Inpatient Room ID.',
            required: true,
            type: 'string'
        }
        */

		try {
			const schema = Joi.object().keys({
				id: Joi.string().required().label("ID"),
			});

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

			let data = await InpatientRoomModel.list({ "InpatientRoom.id": param.id }).then((q) =>
				q //
					.leftJoinAndSelect("InpatientRoom.room", "room")
					.getOne(),
			);

			if (!data) throw { message: "Inpatient Room " + Language.lang.failed_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, 500, 402, Language.lang.failed_view, err.message);
		}
	}

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

		const queryRunner = OrmHelper.DB.createQueryRunner();
		await queryRunner.startTransaction();

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

			const schema = Joi.object().keys({
				id: Joi.string().required().label("Inpatient Room ID"),
				room_id: Joi.string().uuid().required().label("Room ID"),
				name: Joi.string().required().label("Name"),
				number_of_bed: Joi.number().required().min(0).label("Number of Bed"),
			});

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

			let inpatientRoom: InpatientRoom = await InpatientRoomModel.list({ id: param.id }).then((q) => q.getOne());
			if (!inpatientRoom) throw { message: "Inpatient Room " + Language.lang.failed_not_found };

			let room: Room = await RoomModel.list({ id: param.room_id }).then((q) => q.getOne());
			if (!room) throw { message: "Room " + Language.lang.failed_not_found };

			const newNumberOfBed: number = param.number_of_bed;
			const authName = req.auth?.data?.name;

			const existingBeds = await queryRunner.manager
				.getRepository(InpatientRoomBed)
				.createQueryBuilder("bed")
				.leftJoinAndSelect("bed.boarding_room", "boarding_room")
				.leftJoin("bed.inpatient_room", "inpatient_room")
				.where("inpatient_room.id = :roomId", { roomId: param.id })
				.andWhere("bed.deleted_at IS NULL")
				.orderBy("bed.number", "DESC")
				.getMany();

			const occupiedCount = existingBeds.filter((bed) => bed.boarding_room != null).length;
			if (occupiedCount > newNumberOfBed) {
				throw { message: "Update gagal, masih ada bed yang sedang digunakan" };
			}

			if (existingBeds.length > newNumberOfBed) {
				let remainingToDelete = existingBeds.length - newNumberOfBed;

				for (const bed of existingBeds) {
					if (remainingToDelete <= 0) break;
					if (bed.boarding_room != null) continue;

					await queryRunner.manager.update(InpatientRoomBed, { id: bed.id }, { deleted_by: authName });
					await queryRunner.manager.softDelete(InpatientRoomBed, { id: bed.id });
					remainingToDelete--;
				}

				if (remainingToDelete > 0) {
					throw { message: "Update gagal, masih ada bed yang sedang digunakan" };
				}
			}

			const activeBeds = await queryRunner.manager
				.getRepository(InpatientRoomBed)
				.createQueryBuilder("bed")
				.leftJoin("bed.inpatient_room", "inpatient_room")
				.where("inpatient_room.id = :roomId", { roomId: param.id })
				.andWhere("bed.deleted_at IS NULL")
				.getMany();

			if (activeBeds.length < newNumberOfBed) {
				const usedNumbers = activeBeds.map((bed) => bed.number);
				let added = 0;
				const toAdd = newNumberOfBed - activeBeds.length;

				for (let i = 1; i <= newNumberOfBed && added < toAdd; i++) {
					if (usedNumbers.includes(i)) continue;

					const bed = new InpatientRoomBed();
					bed.inpatient_room = inpatientRoom;
					bed.number = i;
					bed.status = InpatientRoomBedStatus.Empty;
					bed.created_by = authName;
					await queryRunner.manager.save(bed);
					added++;
				}
			}

			inpatientRoom.room = room;
			inpatientRoom.name = param.name;
			inpatientRoom.number_of_bed = newNumberOfBed;
			inpatientRoom.updated_by = authName;

			await queryRunner.manager.save(inpatientRoom);

			await queryRunner.commitTransaction();

			return ReturnHelper.successResponseAny(res, 200, Language.lang.success_update, inpatientRoom);
		} 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 = ['Inpatient Room']
      #swagger.security = [{
        "bearerAuth": []
      }]
      #swagger.parameters['id'] = {
        in: 'path',
        description: 'Inpatient Room 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(InpatientRoom);

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