<?php

namespace App\Domains\Event\Actions\CertificateOfConductionCheck;

use App\Enumerations\EfzStatus;
use Illuminate\Support\Facades\Http;

class CertificateOfConductionCheckCommand {
    function __construct(public CertificateOfConductionCheckRequest $request)
    {}

    public function execute() : CertificateOfConductionCheckResponse {
        $response = new CertificateOfConductionCheckResponse();

        $localGroup = str_replace('Stamm ', '', $this->request->participant->localGroup()->first()->name);

        $apiResponse = Http::acceptJson()
            ->asJson()
            ->withoutVerifying()
            ->post(env('COC_CHECK_URL'), [
                'firstName'    => trim($this->request->participant->firstname),
                'lastName'     => $this->request->participant->lastname,
                'nickname'     => $this->request->participant->nickname,
                'address'      => trim($this->request->participant->address_1 . ' ' . $this->request->participant->address_2),
                'zip'          => $this->request->participant->zip,
                'city'         => $this->request->participant->city,
                'birthday'     => $this->request->participant->birthday->format('Y-m-d'),
                'email'        => $this->request->participant->email_1,
                'localGroup'   => $localGroup,
                'checkForDate' => $this->request->participant->departure_date->format('Y-m-d'),
            ]);

        if (! $apiResponse->successful()) {
            return $response;
        }

        $responseParsed = $apiResponse->json();

        if (($responseParsed['status'] ?? null) !== '200/ok') {
            return $response;
        }

        $response->status = match ($responseParsed['efzStatus']) {
            'NOT_REQUIRED' => EfzStatus::EFZ_STATUS_NOT_REQUIRED,
            'CHECKED_VALID' => EfzStatus::EFZ_STATUS_CHECKED_VALID,
            'CHECKED_INVALID' => EfzStatus::EFZ_STATUS_CHECKED_INVALID,
            default => EfzStatus::EFZ_STATUS_NOT_CHECKED
        };

        return $response;
    }
}
