import { Request, ResponseToolkit, ResponseObject } from "@hapi/hapi";
import { NotificationLogService } from "../services/notificationLog.service";
import { AppError } from "../../utils/errors";
import { Common } from "../../utils/common";

export class NotificationLogHandler {
    private getServiceObject = async (request: Request) => {
        const variables = await Common.getVariables(request);
        return new NotificationLogService(variables);
    };

    list = async (request: Request, h: ResponseToolkit): Promise<ResponseObject> => {
        try {
            const service = await this.getServiceObject(request);
            const listRequest = request.query as unknown as NotificationLogListRequestObject;
            const result: NotificationLogPaginatedList = await service.getList({ listRequest });
            return h.response({ message: "REQUEST_PROCESSED_SUCCESSFULLY", responseData: result }).code(200);
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, "SOMETHING_WENT_WRONG_IN_SERVICE", err);
        }
    };

    unreadCount = async (request: Request, h: ResponseToolkit): Promise<ResponseObject> => {
        try {
            const service = await this.getServiceObject(request);
            const count: number = await service.getUnreadCount();
            return h.response({ message: "REQUEST_PROCESSED_SUCCESSFULLY", responseData: { unreadCount: count } }).code(200);
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, "SOMETHING_WENT_WRONG_IN_SERVICE", err);
        }
    };

    markViewed = async (request: Request, h: ResponseToolkit): Promise<ResponseObject> => {
        try {
            const service = await this.getServiceObject(request);
            const params = request.params as unknown as { id: number };
            const result: NotificationLogObjectInterface = await service.markViewed({ id: params.id });
            return h.response({ message: "REQUEST_PROCESSED_SUCCESSFULLY", responseData: result }).code(200);
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, "SOMETHING_WENT_WRONG_IN_SERVICE", err);
        }
    };

    markRead = async (request: Request, h: ResponseToolkit): Promise<ResponseObject> => {
        try {
            const service = await this.getServiceObject(request);
            const params = request.params as unknown as { id: number };
            const result: NotificationLogObjectInterface = await service.markRead({ id: params.id });
            return h.response({ message: "REQUEST_PROCESSED_SUCCESSFULLY", responseData: result }).code(200);
        } catch (err) {
            if (err instanceof AppError) { throw err; }
            throw new AppError(500, "SOMETHING_WENT_WRONG_IN_SERVICE", err);
        }
    };
}
