import { CardKeySet, 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 { CardKeySetModel } from "../model/card_key_sets";
import { OrmHelper } from "../helpers/orm";

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

export class CardKeySetsController {
	static async list(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
		/*
			#swagger.tags = ['Card Key Set']
			#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['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().optional().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 CardKeySetModel.list(filter);

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

			const res_count = query;
			const res_list = query
				.orderBy("CardKeySet." + param.order_field, param.order_direction)
				.offset(offset)
				.limit(limit);

			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 active(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
		/*
			#swagger.tags = ['Card Key Set']
			#swagger.security = [{ "bearerAuth": [] }]
		*/
		try {
			const repo = OrmHelper.DB.getRepository(CardKeySet);
			let entity = await repo.createQueryBuilder("CardKeySet")
				.where("CardKeySet.is_active = :is_active", { is_active: true })
				.orderBy("CardKeySet.created_at", "DESC")
				.getOne();

			if (!entity) throw { message: "Active Card Key Set Not Found" };

			return ReturnHelper.successResponseAny(res, 200, Language.lang.success_view, entity);
		} 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 = ['Card Key Set']
		 #swagger.security = [{ "bearerAuth": [] }]
		 #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/card_key_set" } } } }
		 */
		const queryRunner = OrmHelper.DB.createQueryRunner();
		await queryRunner.startTransaction();
		try {
			const schema = Joi.object().keys({
				key_set_id: Joi.string().max(256).required().label("Key Set ID"),
				app_master_key: Joi.string().allow(null, "").optional().label("App Master Key"),
				read_basic_key: Joi.string().allow(null, "").optional().label("Read Basic Key"),
				write_update_key: Joi.string().allow(null, "").optional().label("Write Update Key"),
				read_sensitive_key: Joi.string().allow(null, "").optional().label("Read Sensitive Key"),
			});

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

			let filter = { key_set_id: param.key_set_id };
			let exist = await CardKeySetModel.list(filter).then((q) => q.getOne());
			if (exist) throw { message: "Card Key Set " + Language.lang.failed_duplicate };

			let entity = new CardKeySet();
			entity.key_set_id = param.key_set_id;
			entity.app_master_key = param.app_master_key;
			entity.read_basic_key = param.read_basic_key;
			entity.write_update_key = param.write_update_key;
			entity.read_sensitive_key = param.read_sensitive_key;
			entity.is_active = true;
			await queryRunner.manager.save(entity);

			// Set the previous data (all other records) to is_active = false
			await queryRunner.manager.createQueryBuilder()
				.update(CardKeySet)
				.set({ is_active: false })
				.where("id != :id", { id: entity.id })
				.execute();

			await queryRunner.commitTransaction();

			return ReturnHelper.successResponseAny(res, 200, Language.lang.success_insert, entity);
		} 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 = ['Card Key Set']
		 #swagger.security = [{ "bearerAuth": [] }]
		 #swagger.parameters['key_set_id'] = { description: '', in: 'path', type: 'string' }
		 */
		try {
			const schema = Joi.object().keys({
				key_set_id: Joi.string().required().label("Card Key Set ID"),
			});

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

			let entity = await CardKeySetModel.list({ "CardKeySet.key_set_id": param.key_set_id }).then((q) => q.getOne());

			if (!entity) throw { message: "Card Key Set Not Found" };

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