import { Diagnosis, Paging } from "entity";
import { NextFunction, Response } from "express";
import { Request } from "express-jwt";
import Joi from "joi";
import { ILogObj, Logger } from "tslog";
import { Brackets } from "typeorm";
import { validate as validateUuid } from "uuid";
import CommonHelper from "../helpers/common";
import { ReturnHelper } from "../helpers/express/return";
import { Language } from "../langs/lang";
import { DiagnosisModel } from "../model/diagnosis";
import { OrmHelper } from "../helpers/orm";
import moment from "moment";

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

const DIAGNOSIS_NAME_COLUMNS = [
	"Diagnosis.diagnosis",
	"Diagnosis.diagnosis_ind",
	"Diagnosis.diagnosis_pt",
	"Diagnosis.diagnosis_tet",
] as const;

const MIN_DIAGNOSIS_SEARCH_TOKEN_LENGTH = 2;

function stripLikeWildcards(value: string): string {
	return value.replace(/^%+|%+$/g, "").trim();
}

function parseDiagnosisSearchTokens(raw: unknown): string[] {
	const text = stripLikeWildcards(String(raw ?? ""));
	if (!text) {
		return [];
	}
	return text
		.split(/\s+/)
		.map((t) => t.trim())
		.filter((t) => t.length >= MIN_DIAGNOSIS_SEARCH_TOKEN_LENGTH);
}

function applyLocalizedDiagnosisFields(
	diagnosis: Diagnosis,
	param: { diagnosis: string; diagnosis_ind?: string; diagnosis_pt?: string; diagnosis_tet?: string },
) {
	diagnosis.diagnosis = param.diagnosis;
	diagnosis.diagnosis_ind = param.diagnosis_ind?.trim() || param.diagnosis;
	diagnosis.diagnosis_pt = param.diagnosis_pt?.trim() || param.diagnosis;
	diagnosis.diagnosis_tet = param.diagnosis_tet?.trim() || param.diagnosis;
}

type DiagnosisQueryBuilder = {
	where: (sql: string, params?: Record<string, unknown>) => unknown;
	orWhere: (sql: string, params?: Record<string, unknown>) => unknown;
	andWhere: (sql: string, params?: Record<string, unknown>) => unknown;
};

function addDiagnosisNameTokenSearch(
	qb: DiagnosisQueryBuilder,
	raw: unknown,
	op: "where" | "orWhere",
	paramPrefix: string,
): void {
	const tokens = parseDiagnosisSearchTokens(raw);
	if (tokens.length === 0) {
		const phrase = `%${stripLikeWildcards(String(raw ?? ""))}%`;
		(qb as any)[op](
			new Brackets((inner) => {
				DIAGNOSIS_NAME_COLUMNS.forEach((col, idx) => {
					const key = `${paramPrefix}_phrase_${idx}`;
					const method = idx === 0 ? "where" : "orWhere";
					(inner as any)[method](`${col} ILIKE :${key}`, { [key]: phrase });
				});
			}),
		);
		return;
	}

	(qb as any)[op](
		new Brackets((tokenGroup) => {
			tokens.forEach((token, tokenIdx) => {
				const tokenKey = `${paramPrefix}_tok_${tokenIdx}`;
				const tokenMethod = tokenIdx === 0 ? "andWhere" : "andWhere";
				(tokenGroup as any)[tokenMethod](
					new Brackets((colGroup) => {
						DIAGNOSIS_NAME_COLUMNS.forEach((col, colIdx) => {
							const colKey = `${tokenKey}_col_${colIdx}`;
							const colMethod = colIdx === 0 ? "where" : "orWhere";
							(colGroup as any)[colMethod](`${col} ILIKE :${colKey}`, {
								[colKey]: `%${token}%`,
							});
						});
					}),
				);
			});
		}),
	);
}

export class DiagnosisController {
	static async list(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
		/*
            #swagger.tags = ['Diagnosis (ICD-11)']
            #swagger.security = [{
                "bearerAuth": []
            }]
            #swagger.parameters['filter'] = {
                description: 'Filter JSON. Diagnosis.code, Diagnosis.diagnosis (multi-word token AND on diagnosis, diagnosis_ind, diagnosis_pt, diagnosis_tet), and Diagnosis.type are OR-combined; other fields use AND.',
                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 codeKey = "Diagnosis.code";
			const diagnosisKey = "Diagnosis.diagnosis";
			const typeKey = "Diagnosis.type";
			const orCode = filter[codeKey];
			const orDiagnosis = filter[diagnosisKey];
			const orType = filter[typeKey];
			const restFilter = { ...filter };
			delete restFilter[codeKey];
			delete restFilter[diagnosisKey];
			delete restFilter[typeKey];

			var query = await DiagnosisModel.list(restFilter);

			if (orCode !== undefined || orDiagnosis !== undefined || orType !== undefined) {
				query.andWhere(
					new Brackets((qb) => {
						let isFirst = true;
						const addOr = (column: string, paramKey: string, raw: any, castText = false) => {
							const op = isFirst ? "where" : "orWhere";
							isFirst = false;
							const colExpr = castText ? `CAST(${column} AS TEXT)` : column;
							if (Array.isArray(raw)) {
								(qb as any)[op](`${colExpr} IN (:...${paramKey})`, { [paramKey]: raw });
								return;
							}
							const f = String(raw);
							if (validateUuid(f)) {
								(qb as any)[op](`${colExpr} = :${paramKey}`, { [paramKey]: f });
								return;
							}
							if (f === "null") {
								(qb as any)[op](`${column} IS NULL`);
								return;
							}
							if (f.includes("%")) {
								(qb as any)[op](`${colExpr} ILIKE :${paramKey}`, { [paramKey]: f });
								return;
							}
							(qb as any)[op](`${colExpr} = :${paramKey}`, { [paramKey]: f });
						};
						if (orCode !== undefined) addOr("Diagnosis.code", "diag_or_code", orCode);
						if (orDiagnosis !== undefined) {
							const op = isFirst ? "where" : "orWhere";
							isFirst = false;
							addDiagnosisNameTokenSearch(qb as DiagnosisQueryBuilder, orDiagnosis, op, "diag_or_diagnosis");
						}
						if (orType !== undefined) addOr("Diagnosis.type", "diag_or_type", orType, true);
					}),
				);
			}

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

			const res_count = query;
			const res_list = query
				.orderBy("Diagnosis." + 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 = ['Diagnosis (ICD-11)']
         #swagger.security = [{
             "bearerAuth": []
         }]
         #swagger.requestBody = {
             required: true,
             content: {
                 "application/json": {
                     schema: {
                         $ref: "#/components/schemas/diagnosis"
                     }
                 }
             }
         }
         */
		const queryRunner = OrmHelper.DB.createQueryRunner();
		await queryRunner.startTransaction();
		try {
			const schema = Joi.object().keys({
				diagnosis: Joi.string().max(256).required().label("Diagnosis"),
				diagnosis_ind: Joi.string().max(256).allow("", null).optional().label("Diagnosis (Indonesian)"),
				diagnosis_pt: Joi.string().max(256).allow("", null).optional().label("Diagnosis (Portuguese)"),
				diagnosis_tet: Joi.string().max(256).allow("", null).optional().label("Diagnosis (Tetum)"),
				code: Joi.string().max(128).required().label("Code"),
				status: Joi.string().required().label("Status"),
			});

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

			let filter = {
				code: param.code,
			};
			let exist = await DiagnosisModel.list(filter).then((q) => q.getOne());
			if (exist) throw { message: "Diagnosis " + Language.lang.failed_duplicate };

			let diagnosis = new Diagnosis();
			applyLocalizedDiagnosisFields(diagnosis, param);
			diagnosis.code = param.code;
			diagnosis.status = param.status;
			diagnosis.created_by = req.auth?.data.name;
			diagnosis.updated_by = req.auth?.data.name;
			await queryRunner.manager.save(diagnosis);

			await queryRunner.commitTransaction();

			return ReturnHelper.successResponseAny(res, 200, Language.lang.success_insert, diagnosis);
		} 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 = ['Diagnosis (ICD-11)']
         #swagger.security = [{
             "bearerAuth": []
         }]
        #swagger.parameters['id'] = {
            description:'',
            in: 'path',
            type: 'string'
        }
        */

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

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

			let diagnosis = await DiagnosisModel.list({
				"Diagnosis.id": param.id,
			}).then((q) => q.getOne());

			if (!diagnosis) throw { message: "Diagnosis Not Found" };

			return ReturnHelper.successResponseAny(res, 200, Language.lang.success_view, diagnosis);
		} 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 = ['Diagnosis (ICD-11)']
         #swagger.security = [{
             "bearerAuth": []
         }]
        #swagger.parameters['id'] = {
            description:'',
            in: 'path',
            type: 'string'
        }
         #swagger.requestBody = {
             required: true,
             content: {
                 "application/json": {
                     schema: {
                         $ref: "#/components/schemas/diagnosis"
                     }
                 }
             }
         }
         */

		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("Diagnosis ID"),
				diagnosis: Joi.string().max(256).required().label("Diagnosis"),
				diagnosis_ind: Joi.string().max(256).allow("", null).optional().label("Diagnosis (Indonesian)"),
				diagnosis_pt: Joi.string().max(256).allow("", null).optional().label("Diagnosis (Portuguese)"),
				diagnosis_tet: Joi.string().max(256).allow("", null).optional().label("Diagnosis (Tetum)"),
				code: Joi.string().max(128).required().label("Code"),
				status: Joi.string().required().label("Status"),
			});

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

			let filter = {
				code: param.code,
			};
			let exist = await DiagnosisModel.list(filter).then((q) => q.getOne());
			if (exist && exist.id != param.id) throw { message: "Diagnosis " + Language.lang.failed_duplicate };

			let diagnosis = await DiagnosisModel.list({
				"Diagnosis.id": param.id,
			}).then((q) => q.getOne());

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

			applyLocalizedDiagnosisFields(diagnosis, param);
			diagnosis.code = param.code;
			diagnosis.status = param.status;
			diagnosis.updated_by = req.auth?.data.name;
			await queryRunner.manager.save(diagnosis);

			await queryRunner.commitTransaction();

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

			let affected = 0;
			if (!param.hard) {
				let diagnosis: Diagnosis = await DiagnosisModel.list({
					"Diagnosis.id": param.id,
				}).then((q) => q.getOne());

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

				diagnosis.deleted_by = req.auth?.data.name;
				diagnosis.deleted_at = moment().toDate();
				await OrmHelper.DB.manager.save(diagnosis);
				affected = 1;
			} else {
				const repo = OrmHelper.DB.getRepository(Diagnosis);
				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 = ['Diagnosis (ICD-11)']
        #swagger.security = [{
            "bearerAuth": []
        }]
        #swagger.parameters['id'] = {
            in: 'path',
            description: 'Diagnosis ID.',
            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(Diagnosis);

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