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

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

const LABORATORY_DEPARTMENT_ID = "7ebc5d8a-63f0-40f6-962b-59953ebd4ba0";

export class LaboratoryController {
	static async list(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
		/*
            #swagger.tags = ['Laboratory']
            #swagger.security = [{ "bearerAuth": [] }]
            #swagger.parameters['filter'] = { description: 'Filter: plain text or JSON object (status, code, 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) : {};
			
			// Build query with department join
			const repo = OrmHelper.DB.getRepository(Room);
			let whereAttr: string[] = [];
			let whereVal: any = {};
			
			// Always filter by laboratory department ID
			whereAttr.push("department.id = :_departmentId");
			whereVal["_departmentId"] = LABORATORY_DEPARTMENT_ID;
			
			// Apply additional filters if provided
			if (filter && Object.keys(filter).length > 0) {
				const filterResult = CommonHelper.handleQueryFilter(filter, "Room");
				whereAttr = [...whereAttr, ...filterResult.whereAttr];
				whereVal = { ...whereVal, ...filterResult.whereVal };
			}

			const offset = (param.page - 1) * param.limit;
			const res_count = repo.createQueryBuilder("Room")
				.leftJoin("Room.department", "department")
				.where(whereAttr.join(" and "), whereVal);
			
			const res_list = repo.createQueryBuilder("Room")
				.leftJoinAndSelect("Room.department", "department")
				.where(whereAttr.join(" and "), whereVal)
				.orderBy("Room." + param.order_field, param.order_direction)
				.offset(offset)
				.limit(param.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);
		}
	}
}
