<?php

namespace App\Services\Integrations;

use App\Models\PlatformConnection;
use App\Services\Credentials\CredentialVault;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;

class MetaMarketingApiService
{
    public function __construct(private readonly CredentialVault $vault) {}

    public function test(PlatformConnection $connection): IntegrationTestResult
    {
        $started = microtime(true);

        try {
            $payload = $this->vault->payload($connection->secureCredential);
            $token = $payload['access_token'] ?? null;
            $adAccountId = $payload['ad_account_id'] ?? $connection->account_id;
            $version = config('services.meta.graph_version', env('META_GRAPH_VERSION', 'v23.0'));

            if (blank($token)) {
                return IntegrationTestResult::failed('Meta access token eksik.');
            }

            if (blank($adAccountId)) {
                return IntegrationTestResult::failed('Meta reklam hesabı ID eksik. Örnek: act_123456789 veya 123456789.');
            }

            $normalizedAccount = str_starts_with((string) $adAccountId, 'act_') ? $adAccountId : 'act_'.$adAccountId;
            $endpoint = "https://graph.facebook.com/{$version}/{$normalizedAccount}/insights";
            $response = Http::timeout(45)->get($endpoint, [
                'fields' => 'spend,impressions,clicks,cpc,cpm,ctr,date_start,date_stop',
                'date_preset' => 'yesterday',
                'limit' => 1,
                'access_token' => $token,
            ]);
            $duration = (int) round((microtime(true) - $started) * 1000);

            if (! $response->successful()) {
                return IntegrationTestResult::failed('Meta bağlantı testi başarısız: '.$this->shortBody($response->body()), $response->json() ?: [], $response->status(), $duration);
            }

            return IntegrationTestResult::success('Meta Ads bağlantısı başarılı. Dün için Insights endpoint erişimi doğrulandı.', [
                'sample' => $response->json('data.0') ?? [],
                'ad_account_id' => $normalizedAccount,
            ], $response->status(), $duration);
        } catch (\Throwable $e) {
            $duration = (int) round((microtime(true) - $started) * 1000);
            return IntegrationTestResult::failed($e->getMessage(), [], null, $duration);
        }
    }

    private function shortBody(string $body): string
    {
        return Str::limit($body, 700);
    }
}
