package com.banesco.module.service_order_status_control.infrastructure.adapter;

import com.banesco.common.application.helper.ServiceStatusValidateHelper;
import com.banesco.common.domain.exception.HttpStatusCodeException;
import com.banesco.common.domain.model.Either;
import com.banesco.module.service_order_status.application.usecase.ServiceOrderStatusUseCase;
import com.banesco.module.service_order_status.domain.dto.response.ServiceOrderStatusResponse;
import com.banesco.module.service_order_status_control.application.repository.ApiPrivateRepository;
import com.banesco.module.service_order_status_control.domain.dto.request.ServiceOrderStatusControlRequest;
import com.banesco.module.service_order_status_control.domain.dto.response.ServiceOrderStatusControlResponse;
import com.banesco.module.service_order_status_control.infrastructure.mapper.ServicingIssueMapper;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

@Slf4j
@ApplicationScoped
public class ApiPrivateAdapter implements ApiPrivateRepository {
    private final ServiceOrderStatusUseCase serviceOrderStatusUseCase;

    @Inject
    public ApiPrivateAdapter(
        ServiceOrderStatusUseCase serviceOrderStatusUseCase
    ) {
        this.serviceOrderStatusUseCase = serviceOrderStatusUseCase;
    }

    @Override
    public ServiceOrderStatusControlResponse execute(
        ServiceOrderStatusControlRequest request
    ) {
        Either<ServiceOrderStatusResponse, ServiceOrderStatusResponse> responseEither =
            serviceOrderStatusUseCase.execute(
                request,
                ServiceOrderStatusResponse.class,
                ServiceOrderStatusResponse.class
            );

        if(!Objects.isNull(responseEither)) {
            ServiceOrderStatusResponse response = (responseEither.isLeft())
                ? responseEither.getLeft()
                : responseEither.getRight();

            if(!Objects.isNull(response)) {
                validateStatus(response);

                return ServicingIssueMapper.toModel(request, response);
            }
        }

        throw HttpStatusCodeException.conflict("PIBE-00");
    }

    private void validateStatus(
        ServiceOrderStatusResponse response
    ) {
        if(
            !Objects.isNull(response.getStatus()) &&
            !response.getStatus().isEmpty()
        ) {
            ServiceStatusValidateHelper.validateStatus(
                response.getStatus().get(0)
            );
        }
    }
}
