import { Response, NextFunction } from "express";
import { Request } from "express-jwt";
import { ReturnHelper } from "../helpers/express/return";
import { OrmHelper } from "../helpers/orm";
import Joi from "joi";
import { ILogObj, Logger } from "tslog";
import { Language } from "../langs/lang";
import { Paging, CardPrintQueue, CardPrintQueueStatus, CardPrintQueueType } from "entity";
import CommonHelper from "../helpers/common";
import { CardPrintQueueModel } from "../model/card_print_queue";

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

export class CardPrintQueueController {
	static async list(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
		/*
			#swagger.tags = ['CardPrintQueue']
			#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 CardPrintQueueModel.list(filterObj, filterAny);

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

			const res_count = query;
			const res_list = query
				.orderBy("card_print_queue." + 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);
		}
	}

	private static async handleCreate(req: Request, res: Response, type: CardPrintQueueType): Promise<Response> {
		try {
			const schema = Joi.object().keys({
				mrn: Joi.string().max(256).allow("").optional().label("MRN"),
				municipiu_code: Joi.string().max(256).allow("").optional().label("Municipiu Code"),
				posto_adm_code: Joi.string().max(256).allow("").optional().label("Posto Adm Code"),
				name: Joi.string().max(256).allow("").optional().label("Name"),
				address: Joi.string().allow("").optional().label("Address"),
				municipiu: Joi.string().max(256).allow("").optional().label("Municipiu"),
				posto_adm: Joi.string().max(256).allow("").optional().label("Posto Adm"),
				suco: Joi.string().max(256).allow("").optional().label("Suco"),
				aldeia: Joi.string().max(256).allow("").optional().label("Aldeia"),
				sexo: Joi.string().max(64).allow("").optional().label("Sexo"),
				birthdate: Joi.string().max(64).allow("").optional().label("Birthdate"),
				patient_id: Joi.string().uuid().allow("").optional().label("Patient ID"),
				facility_code: Joi.string().max(256).allow("").optional().label("Facility Code"),
				status: Joi.string().valid("pending", "in_progress", "completed", "failed", "blocked").optional().label("Status"),
			});

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

			const data = new CardPrintQueue();
			data.mrn = param.mrn || null;
			data.municipiu_code = param.municipiu_code || null;
			data.posto_adm_code = param.posto_adm_code || null;
			data.name = param.name || null;
			data.address = param.address || null;
			data.municipiu = param.municipiu || null;
			data.posto_adm = param.posto_adm || null;
			data.suco = param.suco || null;
			data.aldeia = param.aldeia || null;
			data.sexo = param.sexo || null;
			data.birthdate = param.birthdate || null;
			data.patient_id = param.patient_id || null;
			data.facility_code = param.facility_code || null;
			data.status = param.status || CardPrintQueueStatus.PENDING;
			data.type = type;

			const authHeader = req.headers.authorization;
			let rawToken = "";
			if (authHeader) {
				const parts = authHeader.split(" ");
				rawToken = parts.length > 1 ? parts[1] : parts[0];
			}
			data.token = rawToken ? Buffer.from(rawToken).toString("base64") : null;

			data.created_by = req.auth?.data?.name || null;
			data.updated_by = req.auth?.data?.name || null;

			await OrmHelper.DB.manager.save(data);

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

	static async create(req: Request, res: Response, next: NextFunction): Promise<Response> {
		/*
		#swagger.tags = ['CardPrintQueue']
		#swagger.security = [{
			"bearerAuth": []
		}]
		#swagger.requestBody = {
			required: true,
			content: {
				"application/json": {
					schema: {
						 $ref: "#/components/schemas/card_print_queue"
					}  
				}
			}
		}
		*/
		return CardPrintQueueController.handleCreate(req, res, CardPrintQueueType.PRINT_PROVISION);
	}

	static async createProvision(req: Request, res: Response, next: NextFunction): Promise<Response> {
		/*
		#swagger.tags = ['CardPrintQueue']
		#swagger.security = [{
			"bearerAuth": []
		}]
		#swagger.requestBody = {
			required: true,
			content: {
				"application/json": {
					schema: {
						 $ref: "#/components/schemas/card_print_queue"
					}  
				}
			}
		}
		*/
		return CardPrintQueueController.handleCreate(req, res, CardPrintQueueType.PROVISION);
	}

	static async createPrint(req: Request, res: Response, next: NextFunction): Promise<Response> {
		/*
		#swagger.tags = ['CardPrintQueue']
		#swagger.security = [{
			"bearerAuth": []
		}]
		#swagger.requestBody = {
			required: true,
			content: {
				"application/json": {
					schema: {
						 $ref: "#/components/schemas/card_print_queue"
					}  
				}
			}
		}
		*/
		return CardPrintQueueController.handleCreate(req, res, CardPrintQueueType.PRINT);
	}


	static async detail(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
		/*
		 #swagger.tags = ['CardPrintQueue']
		 #swagger.security = [{ "bearerAuth": [] }]
		 #swagger.parameters['id'] = { in: 'path', type: 'number' }
		*/
		try {
			const schema = Joi.object().keys({
				id: Joi.number().integer().required().label("ID"),
			});
			let param: any = await schema.validateAsync(req.params);
			let cardPrintQueue = await CardPrintQueueModel.list({ "card_print_queue.id": param.id }).then((q) => q.getOne());
			if (!cardPrintQueue) throw { message: "Card Print Queue Not Found" };
			return ReturnHelper.successResponseAny(res, 200, Language.lang.success_view, cardPrintQueue);
		} catch (e: unknown) {
			log.error(e);
			const err = e as Error;
			return ReturnHelper.errorResponse(res, 400, 401, Language.lang.failed_not_found, err.message);
		}
	}
}
