<?php

namespace App\Domains\Integration\Services;

use App\Domains\Client\Models\Client;
use App\Domains\Integration\Models\ClientIntegration;
use App\Domains\Integration\Models\Integration;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;

class ClientIntegrationService
{
    public function getClientIntegration(Client $client, string $integrationCode): ?ClientIntegration
    {
        return $client->integrations()
            ->where('integration_code', $integrationCode)
            ->first();
    }

    /** @return Collection<int, ClientIntegration> */
    public function getAllForClient(Client $client): Collection
    {
        return $client->integrations()->with('integration')->get();
    }

    public function updateOrCreateIntegration(
        Client $client,
        Integration $integration,
        array $data,
    ): ClientIntegration {
        return DB::transaction(function () use ($client, $integration, $data): ClientIntegration {
            $clientIntegration = ClientIntegration::query()->updateOrCreate(
                [
                    'client_id' => $client->id,
                    'integration_code' => $integration->integration_code,
                ],
                ['integration_data' => $data],
            );

            $service = $this->resolveService($integration->integration_code);
            $service?->forClient($client)->onSetup();

            return $clientIntegration;
        });
    }

    protected function resolveService(string $integrationCode): ?BaseIntegrationService
    {
        return match ($integrationCode) {
            'email' => new MailService,
            'telepagos', 'telepagos_homo' => new TelepagosIntegrationService($integrationCode),
            default => null,
        };
    }
}
