<?php

namespace App\Services\Integrations\Sdk;

use App\Models\PlatformConnection;
use App\Services\Credentials\CredentialVault;

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

    public function installed(): bool
    {
        return class_exists('FacebookAds\\Api');
    }

    /**
     * @return object
     */
    public function init(PlatformConnection $connection): object
    {
        if (! $this->installed()) {
            throw new \RuntimeException('facebook/php-business-sdk kurulu değil. composer require facebook/php-business-sdk çalıştırılmalı.');
        }

        $payload = $this->vault->payload($connection->secureCredential);
        $appId = $payload['app_id'] ?? config('services.meta.app_id', env('META_APP_ID'));
        $appSecret = $payload['app_secret'] ?? config('services.meta.app_secret', env('META_APP_SECRET'));
        $accessToken = $payload['access_token'] ?? null;

        foreach (compact('appId', 'appSecret', 'accessToken') as $key => $value) {
            if (blank($value)) {
                throw new \RuntimeException('Meta Business SDK için '.$key.' eksik.');
            }
        }

        /** @var class-string $apiClass */
        $apiClass = 'FacebookAds\\Api';
        $apiClass::init($appId, $appSecret, $accessToken);

        return $apiClass::instance();
    }

    public function normalizedAdAccountId(PlatformConnection $connection): string
    {
        $payload = $this->vault->payload($connection->secureCredential);
        $adAccountId = (string) ($payload['ad_account_id'] ?? $connection->account_id ?? '');

        if (blank($adAccountId)) {
            throw new \RuntimeException('Meta reklam hesabı ID eksik.');
        }

        return str_starts_with($adAccountId, 'act_') ? $adAccountId : 'act_'.$adAccountId;
    }
}
