import { NextFunction, Response } from "express";
import { Request } from "express-jwt";
import Joi from "joi";
import { ILogObj, Logger } from "tslog";
import { ReturnHelper } from "../helpers/express/return";
import { Language } from "../langs/lang";
import { ScheduleModel } from "../model/schedule";
import CommonHelper from "../helpers/common";

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

export class ScheduleController {
    static async list(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
        /*
            #swagger.tags = ['Schedule']
            #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'] } }
            #swagger.responses[200] = {
                description: 'Schedule series paginated list',
                schema: {
                    status: true,
                    code: 200,
                    message: 'success',
                    data: { count: 1, page: 1, total_count: 1, list: [{ id: 'uuid-string', title: 'Practice Schedule' }] }
                }
            }
        */
        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: {
                filter?: string;
                page: number;
                limit: number;
                with_deleted: boolean;
                order_field: string;
                order_direction: "asc" | "desc";
            } = await schema.validateAsync(req.query);

            const filter = param.filter && param.filter !== "" ? JSON.parse(param.filter) : {};
            const filterAny = filter.any && filter.any !== "" ? String(filter.any) : "";
            const filterObj = { ...filter } as any;
            delete filterObj.any;

            const query = await ScheduleModel.listSeries(filterObj);
            if (filterAny !== "") {
                const anyVal = filterAny.includes("%") ? filterAny : `%${filterAny}%`;
                query.andWhere(
                    "(ScheduleSeries.title ILIKE :any OR Room.room ILIKE :any OR Room.code ILIKE :any OR Doctor.name ILIKE :any OR Doctor.username ILIKE :any)",
                    { any: anyVal }
                );
            }
            const orderDirection = param.order_direction.toUpperCase() as "ASC" | "DESC";

            const offset = (param.page - 1) * param.limit;
            const resCount = query;
            const resList = query
                .orderBy("ScheduleSeries." + param.order_field, orderDirection)
                .offset(offset)
                .limit(param.limit);

            if (param.with_deleted) {
                resCount.withDeleted();
                resList.withDeleted();
            }

            const currentPage = param.page;
            const totalCountData = await resCount.getCount();
            const listData = await resList.getMany();
            const countData = CommonHelper.countObject(listData);

            return ReturnHelper.successResponselist(res, 200, Language.lang.success_view, countData, currentPage, totalCountData, listData);
        } 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 options(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
        /*
            #swagger.tags = ['Schedule']
            #swagger.security = [{ "bearerAuth": [] }]
            #swagger.parameters['filter'] = { in: 'query', required: false, type: 'string', description: 'Filter by room id (optional)' }
            #swagger.responses[200] = {
                description: 'Schedule options',
                schema: {
                    status: true,
                    code: 200,
                    message: 'success',
                    data: {
                        doctors: [{ id: 'uuid-string', title: 'Doctor Name' }],
                        rooms: [{ id: 'uuid-string', title: 'Room Name' }]
                    }
                }
            }
        */
        try {
            const schema = Joi.object().keys({
                filter: Joi.string().allow("").optional().label("Filter"),
            });

            const param: { filter?: string } = await schema.validateAsync(req.query);
            const filterObj = param.filter && param.filter !== "" ? JSON.parse(param.filter) : {};
            const result = await ScheduleModel.getScheduleOptions(filterObj);

            return ReturnHelper.successResponseAny(res, 200, Language.lang.success_view, result);
        } 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 calendar(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
        /*
            #swagger.tags = ['Schedule']
            #swagger.security = [{ "bearerAuth": [] }]
            #swagger.parameters['start_date'] = { in: 'query', required: true, type: 'string' }
            #swagger.parameters['end_date'] = { in: 'query', required: true, type: 'string' }
            #swagger.parameters['filter'] = { in: 'query', required: false, type: 'string' }
            #swagger.parameters['limit'] = { in: 'query', required: false, type: 'number' }
            #swagger.parameters['page'] = { in: 'query', required: false, type: 'number' }
            #swagger.responses[200] = {
                description: 'Schedule calendar rooms and events',
                schema: {
                    status: true,
                    code: 200,
                    message: 'success',
                    data: {
                        count: 1,
                        page: 1,
                        total_count: 1,
                        list: {
                            rooms: [{
                                id: 'uuid-string',
                                name: 'string',
                                code: 'string',
                                picture: 'string',
                                location: 'string',
                                status: 'string',
                                department: {
                                    name: 'string',
                                },
                            }],
                            events: [{
                                id: 'occ:series-101:2026-03-20',
                                series_id: 'series-101',
                                room_id: 'room-1',
                                room_name: 'Room 1',
                                doctor_id: 'doctor-1',
                                doctor_name: 'Doctor 1',
                                title: 'Practice',
                                start_at: '2026-03-20T09:00:00+07:00',
                                end_at: '2026-03-20T12:00:00+07:00',
                                quota: 10,
                                used_quota: 5,
                                left_quota: 5,
                                is_recurring: true,
                                is_exception: false,
                                status: 'confirmed'
                            }],
                        }
                    }
                }
            }
        */
        try {
            const schema = Joi.object().keys({
                start_date: Joi.string().required().label("Start Date"),
                end_date: Joi.string().required().label("End Date"),
                filter: Joi.string().allow("").optional().label("Filter"),
                limit: Joi.number().min(1).optional().label("Limit"),
                page: Joi.number().min(1).optional().label("Page"),
            });

            const param: {
                start_date: string;
                end_date: string;
                filter?: string;
                limit?: number;
                page?: number;
            } = await schema.validateAsync(req.query);
            const filterObj = param.filter && param.filter !== "" ? JSON.parse(param.filter) : {};
            const result = await ScheduleModel.getScheduleCalendarRange(param.start_date, param.end_date, filterObj, {
                limit: param.limit,
                page: param.page,
            });

            return ReturnHelper.successResponseAny(res, 200, Language.lang.success_view, result);
        } 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 detail(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
        /*
            #swagger.tags = ['Schedule']
            #swagger.security = [{ "bearerAuth": [] }]
            #swagger.parameters['id'] = { in: 'path', required: true, type: 'string' }
            #swagger.responses[200] = {
                description: 'Schedule series detail',
                schema: {
                    status: true,
                    code: 200,
                    message: 'success',
                    data: {
                        series: {
                            id: 'uuid-string',
                            title: 'Practice Schedule',
                            recurrence: { $ref: '#/components/schemas/scheduleRecurrence' }
                        },
                        exceptions: [{ id: 'uuid-string', occurrence_date: '2026-03-24' }]
                    }
                }
            }
        */
        try {
            const schema = Joi.object().keys({
                id: Joi.string().uuid().required().label("Series ID"),
            });

            const param: { id: string } = await schema.validateAsync(req.params);
            const result = await ScheduleModel.getSeriesById(param.id);
            return ReturnHelper.successResponseAny(res, 200, Language.lang.success_view, result);
        } 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 = ['Schedule']
            #swagger.security = [{ "bearerAuth": [] }]
            #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/scheduleSeriesCreate" } } } }
            #swagger.responses[200] = {
                description: 'Schedule series created',
                schema: { status: true, code: 200, message: 'success', data: { id: 'uuid-string' } }
            }
        */
        try {
            const schema = Joi.object().keys({
                roomId: Joi.string().uuid().required(),
                doctorId: Joi.string().uuid().required(),
                title: Joi.string().max(256).required(),
                quota: Joi.number().integer().min(0).allow(null).optional(),
                startDate: Joi.string().required(),
                untilDate: Joi.string().allow("", null).optional(),
                startTime: Joi.string().required(),
                endTime: Joi.string().required(),
                recurrence: Joi.object({
                    type: Joi.string().valid("daily", "weekly", "monthly").required(),
                    interval: Joi.number().min(1).optional(),
                    daysOfWeek: Joi.array().items(Joi.string().valid("SU", "MO", "TU", "WE", "TH", "FR", "SA")).optional(),
                })
                    .allow(null)
                    .optional(),
            });

            const param = await schema.validateAsync(req.body);
            const actor = req.auth?.data?.name || "system";
            const result = await ScheduleModel.createSeries(param, actor);
            return ReturnHelper.successResponseAny(res, 200, Language.lang.success_insert, result);
        } catch (e: unknown) {
            log.error(e);
            const err = e as Error;
            return ReturnHelper.errorResponse(res, 400, 401, Language.lang.failed_insert, err.message);
        }
    }

    static async update(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
        /*
            #swagger.tags = ['Schedule']
            #swagger.security = [{ "bearerAuth": [] }]
            #swagger.parameters['id'] = { in: 'path', required: true, type: 'string' }
            #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/scheduleSeriesUpdate" } } } }
            #swagger.responses[200] = {
                description: 'Schedule series updated',
                schema: { status: true, code: 200, message: 'success', data: { id: 'uuid-string' } }
            }
        */
        try {
            req.body.id = req.params["id"];
            const schema = Joi.object().keys({
                id: Joi.string().uuid().required(),
                roomId: Joi.string().uuid().required(),
                doctorId: Joi.string().uuid().required(),
                title: Joi.string().max(256).required(),
                quota: Joi.number().integer().min(0).allow(null).optional(),
                startDate: Joi.string().required(),
                untilDate: Joi.string().allow("", null).optional(),
                startTime: Joi.string().required(),
                endTime: Joi.string().required(),
                recurrence: Joi.object({
                    type: Joi.string().valid("daily", "weekly", "monthly").required(),
                    interval: Joi.number().min(1).optional(),
                    daysOfWeek: Joi.array().items(Joi.string().valid("SU", "MO", "TU", "WE", "TH", "FR", "SA")).optional(),
                })
                    .allow(null)
                    .optional(),
            });

            const param = await schema.validateAsync(req.body);
            const actor = req.auth?.data?.name || "system";
            const result = await ScheduleModel.updateSeries(param.id, param, actor);
            return ReturnHelper.successResponseAny(res, 200, Language.lang.success_update, result);
        } catch (e: unknown) {
            log.error(e);
            const err = e as Error;
            return ReturnHelper.errorResponse(res, 400, 401, Language.lang.failed_update, err.message);
        }
    }

    static async createException(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
        /*
            #swagger.tags = ['Schedule']
            #swagger.security = [{ "bearerAuth": [] }]
            #swagger.parameters['id'] = { in: 'path', required: true, type: 'string' }
            #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/scheduleExceptionCreate" } } } }
            #swagger.responses[200] = {
                description: 'Schedule exception created or updated',
                schema: { status: true, code: 200, message: 'success', data: { id: 'uuid-string' } }
            }
        */
        try {
            req.body.id = req.params["id"];
            const schema = Joi.object().keys({
                id: Joi.string().uuid().required(),
                occurrenceDate: Joi.string().required(),
                isCancelled: Joi.boolean().optional(),
                overrideRoomId: Joi.string().uuid().allow("", null).optional(),
                overrideDoctorId: Joi.string().uuid().allow("", null).optional(),
                overrideTitle: Joi.string().max(256).allow("", null).optional(),
                overrideStartAt: Joi.string().allow("", null).optional(),
                overrideEndAt: Joi.string().allow("", null).optional(),
            });

            const param = await schema.validateAsync(req.body);
            const actor = req.auth?.data?.name || "system";
            const result = await ScheduleModel.createSeriesException(param.id, param, actor);
            return ReturnHelper.successResponseAny(res, 200, Language.lang.success_insert, result);
        } catch (e: unknown) {
            log.error(e);
            const err = e as Error;
            return ReturnHelper.errorResponse(res, 400, 401, Language.lang.failed_insert, err.message);
        }
    }

    static async delete(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
        /*
            #swagger.tags = ['Schedule']
            #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' }
            #swagger.responses[200] = {
                description: 'Schedule series deleted',
                schema: { status: true, code: 200, message: 'success', data: {} }
            }
        */
        try {
            const schema = Joi.object().keys({
                id: Joi.string().uuid().required().label("ID"),
                hard: Joi.alternatives()
                    .try(Joi.boolean(), Joi.string().valid("", "true", "false", "1", "0"))
                    .optional()
                    .label("Is hard delete?"),
            });

            const param: { id: string; hard?: boolean | string } = await schema.validateAsync(req.params);

            const isHardDelete =
                param.hard === true || param.hard === "true" || param.hard === "1";

            const actor = req.auth?.data?.name || "system";
            const affected = await ScheduleModel.deleteSeries(param.id, isHardDelete, actor);

            if (affected > 0) {
                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);
        }
    }
}
