import { Service, Paging, Status } 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 { ServiceModel } from "../model/service";
import { ServiceTypeModel } from "../model/service_type";
import { ServiceFareModel } from "../model/service_fare";
import { RoomServicesModel } from "../model/room_services";
import { OrmHelper } from "../helpers/orm";
import moment from "moment";

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

export class ServiceController {
    static async list(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
        /*
            #swagger.tags = ['Service']
            #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: false, type: 'string', default: 'created_at' }
            #swagger.parameters['order_direction'] = { in: 'query', required: false, schema: { '@enum': ['ASC', 'DESC'], default: '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().optional().default("created_at").label("Order Field"),
                order_direction: Joi.string().allow("asc", "desc").optional().default("desc").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;

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

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

            const res_count = query;
            const res_list = query
                .orderBy("Service." + param.order_field, param.order_direction)
                .leftJoinAndSelect("Service.serviceType", "serviceType")
                .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 = ['Service']
         #swagger.security = [{ "bearerAuth": [] }]
         #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/service" } } } }
         */
        const queryRunner = OrmHelper.DB.createQueryRunner();
        await queryRunner.startTransaction();
        try {
            const schema = Joi.object().keys({
                name: Joi.string().max(256).required().label("Name"),
                service_type_id: Joi.string().uuid().required().label("Service Type ID"),
                status: Joi.string().required().label("Status"),
            });

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

            let serviceType = await ServiceTypeModel.list({ id: param.service_type_id }).then((q) => q.getOne());
            if (!serviceType) throw { message: "Service Type not found" };

            let service = new Service();
            service.name = param.name;
            service.serviceType = serviceType;
            service.status = param.status;
            service.created_by = req.auth?.data.name;
            service.updated_by = req.auth?.data.name;
            await queryRunner.manager.save(service);

            await queryRunner.commitTransaction();

            const saved = await ServiceModel.list({ "Service.id": service.id })
                .then((q) => q.leftJoinAndSelect("Service.serviceType", "serviceType").getOne());
            if (saved) {
                await RoomServicesModel.syncRoomsOnServiceCreated(OrmHelper.DB.manager, saved);
            }

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

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

            let service = await ServiceModel.list({ "Service.id": param.id })
                .then((q) => q
                    .leftJoinAndSelect("Service.serviceType", "serviceType")
                    .getOne());

            if (!service) throw { message: "Service Not Found" };

            let serviceFares = await ServiceFareModel.list({ "ServiceFare.serviceId": param.id })
                .then((q) => q
                    .leftJoinAndSelect("ServiceFare.serviceClass", "serviceClass")
                    .getMany());

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

    static async update(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
        /*
         #swagger.tags = ['Service']
         #swagger.security = [{ "bearerAuth": [] }]
         #swagger.parameters['id'] = { description: '', in: 'path', type: 'string' }
         #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/service" } } } }
         */
        const queryRunner = OrmHelper.DB.createQueryRunner();
        await queryRunner.startTransaction();

        try {
            req.body.id = req.params["id"];

            const schema = Joi.object().keys({
                id: Joi.string().uuid().required().label("Service ID"),
                name: Joi.string().max(256).required().label("Name"),
                service_type_id: Joi.string().uuid().required().label("Service Type ID"),
                status: Joi.string().required().label("Status"),
            });

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

            let serviceType = await ServiceTypeModel.list({ id: param.service_type_id }).then((q) => q.getOne());
            if (!serviceType) throw { message: "Service Type not found" };

            let service = await ServiceModel.list({ "Service.id": param.id })
                .then((q) => q.leftJoinAndSelect("Service.serviceType", "st").getOne());

            if (!service) throw { message: "Service " + Language.lang.failed_not_found };

            const oldTypeId = service.serviceType?.id;

            service.name = param.name;
            service.serviceType = serviceType;
            service.status = param.status;
            service.updated_by = req.auth?.data.name;
            await queryRunner.manager.save(service);

            await queryRunner.commitTransaction();

            const saved = await ServiceModel.list({ "Service.id": service.id })
                .then((q) => q.leftJoinAndSelect("Service.serviceType", "serviceType").getOne());
            if (saved) {
                await RoomServicesModel.syncRoomsOnServiceUpdated(
                    OrmHelper.DB.manager,
                    saved,
                    oldTypeId
                );
            }

            return ReturnHelper.successResponseAny(res, 200, Language.lang.success_update, service);
        } 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 updateservicerooms(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
    //     /*
    //      #swagger.tags = ['Service']
    //      #swagger.security = [{ "bearerAuth": [] }]
    //      #swagger.parameters['id'] = { description: '', in: 'path', type: 'string' }
    //      #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/servicerooms" } } } }
    //      */
    //     const queryRunner = OrmHelper.DB.createQueryRunner();
    //     await queryRunner.startTransaction();

    //     try {
    //         req.body.id = req.params["id"];

    //         const schema = Joi.object().keys({
    //             id: Joi.string().uuid().required().label("Service ID"),
    //             room_ids: Joi.array().items(Joi.string().uuid()).optional().label("Room IDs"),
    //         });

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

    //         let service = await ServiceModel.list({ "Service.id": param.id })
    //             .then((q) => q.leftJoinAndSelect("Service.serviceType", "st").leftJoinAndSelect("Service.rooms", "r").getOne());

    //         if (!service) throw { message: "Service " + Language.lang.failed_not_found };

    //         let rooms: any[] = [];
    //         if (param.room_ids && param.room_ids.length > 0) {
    //             for (const roomId of param.room_ids) {
    //                 const room = await RoomModel.list({ id: roomId }).then((q) => q.getOne());
    //                 if (room) rooms.push(room);
    //             }
    //         }

    //         service.rooms = rooms;
    //         service.updated_by = req.auth.data.name;
    //         await queryRunner.manager.save(service);

    //         await queryRunner.commitTransaction();

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

            let affected = 0;
            if (!param.hard) {
                let service: Service = await ServiceModel.list({ "Service.id": param.id }).then((q) => q.getOne());

                if (!service) throw { message: "Service " + Language.lang.failed_not_found };

                service.deleted_by = req.auth?.data.name;
                service.deleted_at = moment().toDate();
                await OrmHelper.DB.manager.save(service);
                affected = 1;
            } else {
                const repo = OrmHelper.DB.getRepository(Service);
                affected = (await repo.delete({ id: param.id })).affected ?? 0;
            }

            if (affected > 0) {
                await RoomServicesModel.syncRoomsOnServiceDeleted(OrmHelper.DB.manager, param.id);
                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);
        }
    }

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

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

            const repo = OrmHelper.DB.getRepository(Service);

            const affected = (await repo.restore({ id: param.id })).affected ?? 0;

            if (affected > 0) {
                const service = await ServiceModel.list({ "Service.id": param.id })
                    .then((q) => q.leftJoinAndSelect("Service.serviceType", "serviceType").getOne());
                if (service && service.status === Status.Active) {
                    await RoomServicesModel.syncRoomsOnServiceCreated(OrmHelper.DB.manager, service);
                }
                return ReturnHelper.successResponseAny(res, 200, Language.lang.success_restore, {});
            } 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_restore, err.message);
        }
    }
}
