import { ExaminationDetail, Paging } 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 { ExaminationDetailModel } from "../model/examination_detail";
import { MeasurementUnitModel } from "../model/measurement_unit";
import { ReferenceRangeModel } from "../model/reference_range";
import { OrmHelper } from "../helpers/orm";
import moment from "moment";

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

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

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

			const res_count = query.clone();
			const res_ids = query
				.clone()
				.select("ExaminationDetail.id", "id")
				.orderBy("ExaminationDetail." + param.order_field, param.order_direction)
				.offset(offset)
				.limit(limit);

			if (param.with_deleted) {
				res_count.withDeleted();
				res_ids.withDeleted();
			}

			const current_page = param.page;
			const total_count_data = await res_count.getCount();
			const ids = (await res_ids.getRawMany()).map((r: any) => r.id).filter(Boolean);

			let list_data: any[] = [];
			if (ids.length > 0) {
				const res_list = OrmHelper.DB.getRepository(ExaminationDetail)
					.createQueryBuilder("ExaminationDetail")
					.leftJoinAndSelect("ExaminationDetail.measurement_unit", "measurementUnit")
					.leftJoinAndSelect("ExaminationDetail.reference_range", "referenceRange")
					.where("ExaminationDetail.id IN (:...ids)", { ids })
					.orderBy("ExaminationDetail." + param.order_field, param.order_direction);

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

				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 = ['Examination Detail']
         #swagger.security = [{ "bearerAuth": [] }]
         #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/examinationDetail" } } } }
         */
		const queryRunner = OrmHelper.DB.createQueryRunner();
		await queryRunner.startTransaction();
		try {
			const schema = Joi.object().keys({
				name: Joi.string().max(256).required().label("Name"),
				order_no: Joi.string().max(256).required().label("Order No."),
				measurement_unit_id: Joi.string().uuid().required().label("Measurement Unit ID"),
				reference_range_ids: Joi.array().items(Joi.string().uuid()).min(1).required().label("Reference Range IDs"),
				status: Joi.string().required().label("Status"),
			});

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

			let measurementUnit = await MeasurementUnitModel.list({ "MeasurementUnit.id": param.measurement_unit_id }).then((q) => q.getOne());
			if (!measurementUnit) throw { message: "Measurement Unit not found" };

			const referenceRanges = await Promise.all(
				param.reference_range_ids.map(async (id: string) => {
					const rr = await ReferenceRangeModel.list({ "ReferenceRange.id": id }).then((q) => q.getOne());
					if (!rr) throw { message: `Reference Range ${id} not found` };
					return rr;
				})
			);

			let examinationDetail = new ExaminationDetail();
			examinationDetail.name = param.name;
			examinationDetail.order_no = param.order_no;
			examinationDetail.measurement_unit = measurementUnit;
			examinationDetail.reference_range = referenceRanges;
			examinationDetail.status = param.status;
			examinationDetail.created_by = req.auth?.data.name;
			examinationDetail.updated_by = req.auth?.data.name;
			await queryRunner.manager.save(examinationDetail);

			await queryRunner.commitTransaction();

			return ReturnHelper.successResponseAny(res, 200, Language.lang.success_insert, examinationDetail);
		} 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 = ['Examination Detail']
         #swagger.security = [{ "bearerAuth": [] }]
         #swagger.parameters['id'] = { in: 'path', type: 'string' }
        */
		try {
			const schema = Joi.object().keys({
				id: Joi.string().uuid().required().label("Examination Detail Id"),
			});

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

			let examinationDetail = await ExaminationDetailModel.list({ "ExaminationDetail.id": param.id }).then((q) => q.leftJoinAndSelect("ExaminationDetail.measurement_unit", "measurementUnit").leftJoinAndSelect("ExaminationDetail.reference_range", "referenceRange").getOne());

			if (!examinationDetail) throw { message: "Examination Detail Not Found" };

			return ReturnHelper.successResponseAny(res, 200, Language.lang.success_view, examinationDetail);
		} 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 = ['Examination Detail']
         #swagger.security = [{ "bearerAuth": [] }]
         #swagger.parameters['id'] = { in: 'path', type: 'string' }
         #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/examinationDetail" } } } }
         */
		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("Examination Detail ID"),
				name: Joi.string().max(256).required().label("Name"),
				order_no: Joi.string().max(256).required().label("Order No."),
				measurement_unit_id: Joi.string().uuid().required().label("Measurement Unit ID"),
				reference_range_ids: Joi.array().items(Joi.string().uuid()).min(1).required().label("Reference Range IDs"),
				status: Joi.string().required().label("Status"),
			});

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

			let examinationDetail = await ExaminationDetailModel.list({ "ExaminationDetail.id": param.id }).then((q) => q.getOne());

			if (!examinationDetail) throw { message: "Examination Detail " + Language.lang.failed_not_found };

			let measurementUnit = await MeasurementUnitModel.list({ "MeasurementUnit.id": param.measurement_unit_id }).then((q) => q.getOne());
			if (!measurementUnit) throw { message: "Measurement Unit not found" };

			const referenceRanges = await Promise.all(
				param.reference_range_ids.map(async (id: string) => {
					const rr = await ReferenceRangeModel.list({ "ReferenceRange.id": id }).then((q) => q.getOne());
					if (!rr) throw { message: `Reference Range ${id} not found` };
					return rr;
				})
			);

			examinationDetail.name = param.name;
			examinationDetail.order_no = param.order_no;
			examinationDetail.measurement_unit = measurementUnit;
			examinationDetail.reference_range = referenceRanges;
			examinationDetail.status = param.status;
			examinationDetail.updated_by = req.auth?.data.name;
			await queryRunner.manager.save(examinationDetail);

			await queryRunner.commitTransaction();

			return ReturnHelper.successResponseAny(res, 200, Language.lang.success_update, examinationDetail);
		} 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 = ['Examination Detail']
        #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 examinationDetail: ExaminationDetail = await ExaminationDetailModel.list({ "ExaminationDetail.id": param.id }).then((q) => q.getOne());

				if (!examinationDetail) throw { message: "Examination Detail " + Language.lang.failed_not_found };

				examinationDetail.deleted_by = req.auth?.data.name;
				examinationDetail.deleted_at = moment().toDate();
				await OrmHelper.DB.manager.save(examinationDetail);
				affected = 1;
			} else {
				const repo = OrmHelper.DB.getRepository(ExaminationDetail);
				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 = ['Examination Detail']
        #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(ExaminationDetail);

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