import { NextFunction, Response } from "express";
import { RegistrationFee, Service, Paging } from "entity";
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";
import moment from "moment";

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

const RegistrationFeeCreateAndUpdateSchema = {
    service: Joi.array().items(Joi.string().allow(null, "").uuid()).optional().label("Service"),
    type: Joi.string().valid("emergency", "outpatient").required().label("Type"),
};

export class RegistrationFeeController {
    static async detail(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
        /*
         #swagger.tags = ['Registration Fee']
         #swagger.security = [{ "bearerAuth": [] }]
        #swagger.parameters['filter'] = { 
            description: "Filter in JSON format. Available fields: type (string, exact match), service_name (string, partial match case-insensitive), service_id (number, exact match). Example: {\"type\":\"premium\",\"service_name\":\"konsultasi\",\"service_id\":5}", 
            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"),
            });

            const param: Paging = await schema.validateAsync(req.query);
            const filter = param.filter && param.filter !== "" ? JSON.parse(param.filter) : {};
            const offset = (param.page - 1) * param.limit;

            const baseQuery = OrmHelper.DB.getRepository(RegistrationFee)
                .createQueryBuilder("RegistrationFee")
                .leftJoinAndMapMany(
                    "RegistrationFee.services",
                    Service,
                    "service",
                    "service.id::text = ANY(RegistrationFee.service)"
                );

            // ── Filter RegistrationFee.type ───────────────────────────────────
            if (filter.type && filter.type !== "") {
                baseQuery.andWhere("RegistrationFee.type ILIKE :type", { type:`%${filter.type}%` });
            }

            // ── Filter service.name ───────────────────────────────────────────
            if (filter.service_name && filter.service_name !== "") {
                baseQuery.andWhere("service.name ILIKE :service_name", { service_name: `%${filter.service_name}%` });
            }

            // ── Filter service.id ─────────────────────────────────────────────
            if (filter.service_id && filter.service_id !== "") {
                baseQuery.andWhere("service.id = :service_id", { service_id: filter.service_id });
            }

            if (param.with_deleted) {
                baseQuery.withDeleted();
            }

            const current_page = param.page;
            const total_count_data = await baseQuery.getCount();
            const list_data = await baseQuery
                .orderBy("RegistrationFee." + param.order_field, param.order_direction)
                .offset(offset)
                .limit(param.limit)
                .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<Response> {
        /*
        #swagger.tags = ['Registration Fee']
        #swagger.security = [{
            "bearerAuth": []
        }]
        #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/registration_fee" } } } }
        */
        try {
            const schema = Joi.object().keys({
                ...RegistrationFeeCreateAndUpdateSchema
            });

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

            if (param.service && param.service.length > 0) {
                for (const serviceId of param.service) {
                    const serviceExist = await OrmHelper.DB.getRepository(Service)
                        .createQueryBuilder("Service")
                        .where("Service.id = :id", { id: serviceId })
                        .getOne();

                    if (!serviceExist) throw { message: `Service ID ${serviceId} not found` };
                }
            }

            const data = new RegistrationFee();
            data.type = param.type;
            data.service = Array.isArray(param.service) ? param.service : [];
            data.created_by = req.auth?.data.name;

            await OrmHelper.DB.getRepository(RegistrationFee).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 update(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
        /*
        #swagger.tags = ['Registration Fee']
        #swagger.security = [{ "bearerAuth": [] }]
        #swagger.parameters['id'] = { description: 'ID', in: 'path', type: 'string' }
        #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/registration_fee" } } } }
        */
        const queryRunner = OrmHelper.DB.createQueryRunner();
        await queryRunner.startTransaction();

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

            const param: any = await schema.validateAsync({
                ...req.body,
                id: req.params.id
            });
            if (param.service && param.service.length > 0) {
                for (const serviceId of param.service) {
                    const serviceExist = await OrmHelper.DB.getRepository(Service)
                        .createQueryBuilder("Service")
                        .where("Service.id = :id", { id: serviceId })
                        .getOne();

                    if (!serviceExist) throw { message: `Service ID ${serviceId} not found` };
                }
            }

            const registrationfee = await OrmHelper.DB.getRepository(RegistrationFee)
                .findOne({ where: { id: param.id } });

            if (!registrationfee) throw { message: "Registration Fee " + Language.lang.failed_not_found };

            registrationfee.type = param.type;
            registrationfee.service = Array.isArray(param.service) ? param.service : [];
            registrationfee.updated_by = req.auth?.data.name;

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

            await queryRunner.commitTransaction();

            return ReturnHelper.successResponseAny(res, 200, Language.lang.success_update, registrationfee);
        } 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();
        }
    }
}
