<?php

namespace App\Services\Platforms;

use App\Contracts\PlatformAdapter;
use App\Exceptions\ProviderNotConfiguredException;
use App\Models\AdCopy;
use App\Models\Campaign;
use App\Models\Creative;
use Illuminate\Support\Facades\Http;

/**
 * Minimal Meta Marketing API adapter (create-campaign + attach-creative only).
 * Full read/report/retry support is tracked separately, on sheet row 13.
 */
class MetaAdapter implements PlatformAdapter
{
    public function createCampaign(Campaign $campaign): string
    {
        $response = $this->client()->post("/act_{$this->adAccountId()}/campaigns", [
            'name' => $campaign->name,
            'objective' => $campaign->objective,
            'status' => 'PAUSED',
            // NONE is our own answer for "asked and none apply"; Meta expects
            // that as an empty list.
            'special_ad_categories' => array_values(array_filter(
                (array) ($campaign->special_ad_categories ?? []),
                fn (string $c): bool => $c !== 'NONE',
            )),
        ])->throw();

        return $response->json('id');
    }

    public function attachCreative(Campaign $campaign, Creative $creative, ?AdCopy $adCopy = null): string
    {
        $response = $this->client()->post("/act_{$this->adAccountId()}/ads", [
            'name' => $adCopy?->headline ?? $creative->id,
            'campaign_id' => $campaign->external_campaign_id,
            'status' => 'PAUSED',
        ])->throw();

        return $response->json('id');
    }

    public function publish(Campaign $campaign): void
    {
        $this->client()->post("/{$campaign->external_campaign_id}", [
            'status' => 'ACTIVE',
        ])->throw();
    }

    private function client()
    {
        $token = config('services.meta.access_token');

        if (blank($token)) {
            throw new ProviderNotConfiguredException(
                'Meta access token is not configured. Set META_ACCESS_TOKEN in .env.'
            );
        }

        return Http::baseUrl(config('services.meta.graph_url', 'https://graph.facebook.com/v26.0'))
            ->withToken($token)
            ->asJson()
            ->acceptJson();
    }

    private function adAccountId(): string
    {
        $accountId = config('services.meta.ad_account_id');

        if (blank($accountId)) {
            throw new ProviderNotConfiguredException(
                'Meta ad account id is not configured. Set META_AD_ACCOUNT_ID in .env.'
            );
        }

        return $accountId;
    }
}
