import { SurgeryType, 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 { OrmHelper } from "../helpers/orm";
import { Language } from "../langs/lang";
import { SurgeryTypeModel } from "../model/surgery_type";

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

export class SurgeryTypeController {
	static async list(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
		/*
			#swagger.tags = ['Surgery Type']
			#swagger.security = [{ "bearerAuth": [] }]
			#swagger.parameters['filter'] = { description: '', 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) : {};
			let filterAny = filter.any && filter.any !== "" ? filter.any : "";

			let filterObj = { ...filter } as any;
			delete filterObj.any;
			filterObj = { ...filterObj };

			var query = await SurgeryTypeModel.list(filterObj, filterAny);

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

			const res_count = query;
			const res_list = query
				.orderBy("SurgeryType." + 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 = ['Surgery Type']
		 #swagger.security = [{ "bearerAuth": [] }]
		 #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/surgery_type" } } } }
		 */
		try {
			const schema = Joi.object().keys({
				name: Joi.string().required().label("Name"),
			});

			let param: { name: string } = await schema.validateAsync(req.body);

			let exist = await SurgeryTypeModel.list({ name: param.name }).then((q) => q.getOne());
			if (exist) throw { message: "Surgery Type " + Language.lang.failed_duplicate };

			let surgeryType = new SurgeryType();
			surgeryType.name = param.name;
			surgeryType.created_by = req.auth?.data.name;
			surgeryType.updated_by = req.auth?.data.name;
			await OrmHelper.DB.manager.save(surgeryType);

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

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

			let param: { id: string } = await schema.validateAsync(req.params);

			let surgeryType = await SurgeryTypeModel.list({ "SurgeryType.id": param.id }).then((q) => q.getOne());

			if (!surgeryType) throw { message: "Surgery Type " + Language.lang.failed_not_found };

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

			const schema = Joi.object().keys({
				id: Joi.string().uuid().required().label("Surgery Type ID"),
				name: Joi.string().required().label("Name"),
			});

			let param: { id: string; name: string } = await schema.validateAsync(req.body);

			let exist = await SurgeryTypeModel.list({ name: param.name }).then((q) => q.getOne());
			if (exist && exist.id != param.id) throw { message: "Surgery Type " + Language.lang.failed_duplicate };

			let surgeryType = await SurgeryTypeModel.list({ "SurgeryType.id": param.id }).then((q) => q.getOne());

			if (!surgeryType) throw { message: "Surgery Type " + Language.lang.failed_not_found };

			surgeryType.name = param.name;
			surgeryType.updated_by = req.auth?.data.name;
			await OrmHelper.DB.manager.save(surgeryType);

			return ReturnHelper.successResponseAny(res, 200, Language.lang.success_update, surgeryType);
		} 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 delete(req: Request, res: Response, next: NextFunction): Promise<Response> {
		/*
		#swagger.tags = ['Surgery Type']
		#swagger.security = [{ "bearerAuth": [] }]
		#swagger.parameters['id'] = { in: 'path', required: true, type: 'string' }
		#swagger.parameters['hard'] = { in: 'path', description: 'Is Hard Delete (ignored; entity has no soft 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(SurgeryType);
			const 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);
		}
	}
}
