<?php


namespace App\Services;


use App\DAO\CEPDAO;
use App\DAO\DAOResponse\DAOResponseInterface;
use App\Entities\CEP\CEP;
use App\Mappers\CEPMapper;
use App\Models\CEPModel;
use App\Services\ServiceResponse\ServiceResponse;
use App\Services\ServiceResponse\ServiceResponseInterface;
use Exception;

class CepService extends Service
{
    public  function getCEPData(string $cep) : ServiceResponse
    {
        if (preg_match(REGEX_CEP, $cep)) {
            $cep_dao = new CEPDAO();
            $dao_response = $cep_dao->getDatabaseCEP($cep);
            $dao_response_status = $dao_response->getStatus();
            switch ($dao_response_status) {
                case DAOResponseInterface::SUCESS:
                    $cep_obj = $dao_response->getData();
                    break;
                case DAOResponseInterface::RECORD_NOT_FOUND:
                    $cep_obj = $this->request_cep_data($cep);
                    if ($cep_obj) {
                        $cep_dao->RegisterCEP($cep_obj);
                    }
                    break;
                default:
                    throw new Exception('DAOReponse status not recognized : ' . $dao_response_status);
            }

            $service_response_status = $cep_obj ? ServiceResponseInterface::SUCESS : ServiceResponseInterface::EXTERNAL_SERVICE_UNAVAILABLE;
        } else {
            $service_response_status = ServiceResponseInterface::VALIDATION_PARAMS_ERROR;
            $cep_obj = null;
        }
        $service_response = ServiceResponse::builder()
            ->setStatus($service_response_status)
            ->build();
        if ($service_response_status === ServiceResponseInterface::SUCESS) {
            $service_response->setData($cep_obj->toArray());
        }
        return $service_response;
    }

    private function request_cep_data ($cep) : ?CEP {
        $cep_only_numbers = str_replace(
            '"',
            '',
            str_replace(
                '-',
                '',
                json_encode($cep)
            )
        );
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://viacep.com.br/ws/$cep_only_numbers/json",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
        ));
        return CEPMapper::getCEPFromCURL($curl);
    }

}