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

export class WordpressImportHandler {
    private getService = async (request: Request) => {
        const variables = await Common.getVariables(request);
        return new WordpressImportService(variables);
    }

    importChunk = async (request: Request, h: ResponseToolkit): Promise<ResponseObject> => {
        try {
            const service = await this.getService(request);
            const payload = request.payload as WordpressImportRequestObject;
            const result = await service.importChunk(payload);
            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);
        }
    }

    importUsers = async (request: Request, h: ResponseToolkit): Promise<ResponseObject> => {
        try {
            const service = await this.getService(request);
            const payload = request.payload as UserImportRequestObject;
            const result = await service.importUsers(payload);
            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);
        }
    }

    importSeaQA = async (request: Request, h: ResponseToolkit): Promise<ResponseObject> => {
        try {
            const service = await this.getService(request);
            const payload = request.payload as SeaQAImportRequestObject;
            const result = await service.importSeaQA(payload);
            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);
        }
    }
}
