import { Service, 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 { ServiceModel } from "../model/service";
import { ExaminationDetailModel } from "../model/examination_detail";
import { OrmHelper } from "../helpers/orm";

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

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

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

			var query = await ServiceModel.list(filter);

			const res_count = query;
			const res_list = query
				.leftJoinAndSelect("Service.serviceType", "serviceType")
				.leftJoinAndSelect("Service.examination_details", "examinationDetails")
				.leftJoinAndSelect("examinationDetails.measurement_unit", "measurementUnit")
				.leftJoinAndSelect("examinationDetails.reference_range", "referenceRange")
				.orderBy("Service." + param.order_field, param.order_direction)
				.skip(offset)
				.take(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 = ['Service Examination']
		 #swagger.security = [{ "bearerAuth": [] }]
		 #swagger.requestBody = { 
			required: true, 
			content: { 
				"application/json": { 
					schema: { $ref: "#/components/schemas/serviceExaminationCreate" } 
				} 
			} 
		 }
		*/

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

		try {
			const schema = Joi.object().keys({
				service_id: Joi.string().uuid().required().label("Service ID"),
				examination_detail_ids: Joi.array()
					.items(Joi.string().uuid())
					.optional()
					.label("Examination Detail IDs"),
			});

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

			// ✅ ambil service
			let service = await ServiceModel.list({ "Service.id": param.service_id })
				.then((q) => q.leftJoinAndSelect("Service.serviceType", "st")
					.leftJoinAndSelect("Service.examination_details", "ed")
					.getOne());

			if (!service) throw { message: "Service " + Language.lang.failed_not_found };

			// ✅ ambil examination details
			let examinationDetails: any[] = [];
			if (param.examination_detail_ids && param.examination_detail_ids.length > 0) {
				for (const examinationDetailId of param.examination_detail_ids) {
					const examinationDetail = await ExaminationDetailModel
						.list({ "ExaminationDetail.id": examinationDetailId })
						.then((q) => q.getOne());

					if (examinationDetail) {
						examinationDetails.push(examinationDetail);
					}
				}
			}

			// ✅ assign (CREATE behavior)
			service.examination_details = examinationDetails;
			service.created_by = req.auth?.data.name;
			service.updated_by = req.auth?.data.name;

			await queryRunner.manager.save(service);

			await queryRunner.commitTransaction();

			return ReturnHelper.successResponseAny(
				res,
				200,
				Language.lang.success_insert,
				service
			);

		} 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 update(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
		/*
		 #swagger.tags = ['Service Examination']
		 #swagger.security = [{ "bearerAuth": [] }]
		 #swagger.parameters['id'] = { in: 'path', type: 'string' }
		 #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/serviceExamination" } } } }
		 */
		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("Service ID"),
				examination_detail_ids: Joi.array().items(Joi.string().uuid()).optional().label("Examination Detail IDs"),
			});

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

			let service = await ServiceModel.list({ "Service.id": param.id })
				.then((q) => q.leftJoinAndSelect("Service.serviceType", "st").leftJoinAndSelect("Service.examination_details", "ed").getOne());

			if (!service) throw { message: "Service " + Language.lang.failed_not_found };

			let examinationDetails: any[] = [];
			if (param.examination_detail_ids && param.examination_detail_ids.length > 0) {
				for (const examinationDetailId of param.examination_detail_ids) {
					const examinationDetail = await ExaminationDetailModel.list({ "ExaminationDetail.id": examinationDetailId }).then((q) => q.getOne());
					if (examinationDetail) examinationDetails.push(examinationDetail);
				}
			}

			service.examination_details = examinationDetails;
			service.updated_by = req.auth?.data.name;
			await queryRunner.manager.save(service);

			await queryRunner.commitTransaction();

			return ReturnHelper.successResponseAny(res, 200, Language.lang.success_update, service);
		} 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();
		}
	}
}
