<?php

namespace Tests\Feature;

use App\Agent\NamespacedTool;
use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request as HttpRequest;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Tools\Request;
use Tests\TestCase;

/**
 * A published Meta ad set is checked against the live object before it is changed.
 *
 * The draft tools are not this path. edit_entity already refuses a campaign
 * that has not been published. These tests cover the rules that apply only
 * once the ad set exists on Meta.
 */
class AdSetEditIsGuardedTest extends TestCase
{
    use RefreshDatabase;

    private User $user;

    protected function setUp(): void
    {
        parent::setUp();

        config([
            'platforms.meta.token' => 'test-token',
            'platforms.meta.mcp.enabled' => false,
            'platforms.guardrails.allowed_ad_accounts' => ['meta:*'],
            'platforms.guardrails.paused' => false,
            'platforms.guardrails.change_cooldown_seconds' => 0,
            'platforms.guardrails.max_changes_per_day' => 20,
        ]);

        $this->user = User::factory()->create();
        $this->actingAs($this->user);

        app(Workspace::class)->bindTo('conv-guard');
        app(Workspace::class)->ownedBy($this->user);
    }

    private function campaign(): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Winter Sale',
            'platform' => 'meta',
            'status' => 'published',
            'objective' => 'OUTCOME_TRAFFIC',
            'ad_account_id' => 'act_111',
            'page_id' => 'page-1',
            'landing_url' => 'https://example.com/offer',
            'currency' => 'USD',
            'budget' => 25,
            'budget_mode' => 'daily',
            'budget_level' => 'ad_set',
            'external_campaign_id' => '120252047635070626',
        ]);

        $campaign->primaryAdSet->update([
            'external_adset_id' => 'adset-1',
            'status' => 'published',
            'budget_mode' => 'daily',
            'budget' => 25,
        ]);

        app(Workspace::class)->produced($campaign);
        app(Workspace::class)->focusOn($campaign->fresh());

        return $campaign->fresh();
    }

    /**
     * @param  array<string, mixed>  $adSet
     * @param  array<string, mixed>  $liveCampaign
     * @param  list<array<string, mixed>>  $locales
     */
    private function fakeMeta(array $adSet, array $liveCampaign = [], array $locales = []): void
    {
        Http::fake(function (HttpRequest $request) use ($adSet, $liveCampaign, $locales) {
            $path = parse_url($request->url(), PHP_URL_PATH) ?? '';

            if ($request->method() === 'GET' && str_ends_with($path, '/adsets')) {
                return Http::response(['data' => [['id' => 'adset-1']]]);
            }

            if ($request->method() === 'GET' && str_ends_with($path, '/adset-1')) {
                return Http::response(['id' => 'adset-1', ...$adSet]);
            }

            if ($request->method() === 'GET' && str_ends_with($path, '/120252047635070626')) {
                return Http::response(['id' => '120252047635070626', ...$liveCampaign]);
            }

            if ($request->method() === 'GET' && str_ends_with($path, '/search')) {
                return Http::response(['data' => $locales]);
            }

            return Http::response(['success' => true]);
        });
    }

    private function tool(): NamespacedTool
    {
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($candidate): bool => $candidate->name() === 'campaign__edit_entity');

        $this->assertNotNull($tool);

        return $tool;
    }

    private function edit(array $arguments): array
    {
        return json_decode((string) $this->tool()->handle(new Request($arguments)), true);
    }

    private function posted(): bool
    {
        return $this->postedFields() !== [];
    }

    /** @return array<string, mixed> */
    private function postedFields(): array
    {
        foreach (Http::recorded() as [$request]) {
            if ($request->method() === 'POST' && str_ends_with((string) parse_url($request->url(), PHP_URL_PATH), '/adset-1')) {
                return $request->data();
            }
        }

        return [];
    }

    public function test_a_daily_budget_cannot_replace_a_lifetime_budget(): void
    {
        $this->campaign();
        $this->fakeMeta(['lifetime_budget' => '8000']);

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'budget' => 40]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('lifetime budget', $result['error']);
        $this->assertFalse($this->posted());
    }

    public function test_the_start_time_is_locked_once_the_ad_set_has_started(): void
    {
        $this->campaign();
        $this->fakeMeta([
            'daily_budget' => '2500',
            'start_time' => '2020-01-01T00:00:00+0000',
        ]);

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'starts_at' => '2026-12-01']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('already started', $result['error']);
        $this->assertFalse($this->posted());
    }

    public function test_a_future_start_time_can_still_be_changed(): void
    {
        $this->campaign();
        $this->fakeMeta([
            'daily_budget' => '2500',
            'start_time' => '2027-01-01T00:00:00+0000',
        ]);

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'starts_at' => '2027-02-01']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertTrue($this->posted());
    }

    public function test_an_ad_set_bid_strategy_is_refused_when_the_campaign_has_one(): void
    {
        $this->campaign();
        $this->fakeMeta(
            ['daily_budget' => '2500'],
            ['bid_strategy' => 'LOWEST_COST_WITHOUT_CAP'],
        );

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'bid_strategy' => 'COST_CAP']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('LOWEST_COST_WITHOUT_CAP', $result['error']);
        $this->assertFalse($this->posted());
    }

    public function test_a_local_campaign_strategy_does_not_block_the_ad_set(): void
    {
        $campaign = $this->campaign();
        $campaign->update(['bid_strategy' => 'LOWEST_COST_WITHOUT_CAP']);
        $reads = 0;

        Http::fake(function (HttpRequest $request) use (&$reads) {
            $path = parse_url($request->url(), PHP_URL_PATH) ?? '';

            if ($request->method() === 'GET' && str_ends_with($path, '/adsets')) {
                return Http::response(['data' => [['id' => 'adset-1', 'name' => 'Winter ad set']]]);
            }

            if ($request->method() === 'GET' && str_ends_with($path, '/adset-1')) {
                $reads++;

                return Http::response([
                    'id' => 'adset-1',
                    'bid_strategy' => $reads >= 2 ? 'LOWEST_COST_WITHOUT_CAP' : 'COST_CAP',
                    'bid_amount' => '200',
                    'daily_budget' => '2500',
                ]);
            }

            if ($request->method() === 'GET' && str_ends_with($path, '/120252047635070626')) {
                return Http::response(['id' => '120252047635070626']);
            }

            return Http::response(['success' => true]);
        });

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'bid_strategy' => 'LOWEST_COST_WITHOUT_CAP']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('LOWEST_COST_WITHOUT_CAP', $this->postedFields()['bid_strategy']);
        $this->assertSame('', $this->postedFields()['bid_amount']);
    }

    public function test_a_locked_field_is_returned_and_not_written(): void
    {
        $this->campaign();
        $this->fakeMeta([
            'daily_budget' => '2500',
            'optimization_goal' => 'OFFSITE_CONVERSIONS',
            'billing_event' => 'IMPRESSIONS',
        ]);

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'optimization_goal' => 'LINK_CLICKS']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('OFFSITE_CONVERSIONS', $result['error']);
        $this->assertSame('OFFSITE_CONVERSIONS', $result['locked']['optimization_goal']);
        $this->assertFalse($this->posted());
    }

    public function test_a_large_budget_change_warns_and_still_saves(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '2500']);

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'budget' => 40]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertStringContainsString('more than 20%', $result['learning_warning'][0]);
        $this->assertTrue($this->posted());
    }

    public function test_a_small_budget_change_does_not_warn_about_learning(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '10000']);

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'budget' => 110]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame([], $result['learning_warning']);
    }

    public function test_a_bid_change_warns_and_a_rename_does_not(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '2500', 'bid_amount' => '200']);

        $bid = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'bid_amount' => 2]);
        $name = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'name' => 'Winter v2']);

        $this->assertStringContainsString('Changing the bid', $bid['learning_warning'][0]);
        $this->assertSame([], $name['learning_warning']);
    }

    public function test_the_approval_names_the_learning_warning(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '2500']);

        $approval = $this->tool()->shouldRequestApproval(new Request([
            'entity_type' => 'ad_set',
            'id' => 'adset-1',
            'budget' => 40,
        ], 'call-guard-1'));

        $this->assertNotNull($approval);
        $this->assertStringContainsString('more than 20%', (string) $approval->reason);
    }

    public function test_a_campaign_budget_ad_set_can_take_a_spend_cap(): void
    {
        $campaign = $this->campaign();
        $campaign->update(['budget_level' => 'campaign']);
        $this->fakeMeta([], ['daily_budget' => '5000']);

        $result = $this->edit([
            'entity_type' => 'ad_set',
            'id' => 'adset-1',
            'daily_min_spend_target' => 10,
            'daily_spend_cap' => 20,
        ]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame(1000, $this->postedFields()['daily_min_spend_target']);
        $this->assertSame(2000, $this->postedFields()['daily_spend_cap']);
    }

    public function test_an_ad_set_with_its_own_budget_cannot_take_a_spend_cap(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '2500']);

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'daily_spend_cap' => 20]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('own budget', $result['error']);
        $this->assertFalse($this->posted());
    }

    public function test_a_minimum_spend_above_the_cap_is_refused(): void
    {
        $campaign = $this->campaign();
        $campaign->update(['budget_level' => 'campaign']);
        $this->fakeMeta([], ['daily_budget' => '5000']);

        $result = $this->edit([
            'entity_type' => 'ad_set',
            'id' => 'adset-1',
            'daily_min_spend_target' => 40,
            'daily_spend_cap' => 10,
        ]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('cannot be higher', $result['error']);
        $this->assertFalse($this->posted());
    }

    public function test_a_large_spend_cap_change_warns_and_still_saves(): void
    {
        $campaign = $this->campaign();
        $campaign->update(['budget_level' => 'campaign']);
        $this->fakeMeta(['daily_spend_cap' => '1000'], ['daily_budget' => '5000']);

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'daily_spend_cap' => 40]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertStringContainsString('spend limit', $result['learning_warning'][0]);
        $this->assertSame(4000, $this->postedFields()['daily_spend_cap']);
    }

    public function test_a_budget_schedule_is_sent_in_minor_units_and_replaces_the_list(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '2500']);

        $result = $this->edit([
            'entity_type' => 'ad_set',
            'id' => 'adset-1',
            'budget_schedule_specs' => [[
                'time_start' => '2026-12-01',
                'time_end' => '2026-12-07',
                'budget_value' => 40,
                'budget_value_type' => 'ABSOLUTE',
            ]],
        ]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $specs = json_decode($this->postedFields()['budget_schedule_specs'], true);
        $this->assertSame(4000, $specs[0]['budget_value']);
        $this->assertSame('ABSOLUTE', $specs[0]['budget_value_type']);
        $this->assertStringStartsWith('2026-12-01', $specs[0]['time_start']);
    }

    public function test_an_empty_budget_schedule_clears_it(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '2500']);

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'budget_schedule_specs' => []]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('[]', $this->postedFields()['budget_schedule_specs']);
    }

    public function test_a_budget_schedule_cannot_ride_along_with_a_budget_type_switch(): void
    {
        $this->campaign();
        $this->fakeMeta(['lifetime_budget' => '8000']);

        $result = $this->edit([
            'entity_type' => 'ad_set',
            'id' => 'adset-1',
            'budget' => 40,
            'budget_schedule_specs' => [[
                'time_start' => '2026-12-01',
                'time_end' => '2026-12-07',
                'budget_value' => 40,
            ]],
        ]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('budget schedule', $result['error']);
        $this->assertFalse($this->posted());
    }

    public function test_a_roas_goal_is_sent_as_ten_thousand_times_the_number(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '2500', 'bid_strategy' => 'LOWEST_COST_WITH_MIN_ROAS']);

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'roas_average_floor' => 2.5]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $constraints = json_decode($this->postedFields()['bid_constraints'], true);
        $this->assertSame(25000, $constraints['roas_average_floor']);
        $this->assertStringContainsString('bid', $result['learning_warning'][0]);
    }

    public function test_a_roas_goal_is_refused_without_the_minimum_roas_strategy(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '2500', 'bid_strategy' => 'LOWEST_COST_WITHOUT_CAP']);

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'roas_average_floor' => 2.5]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('minimum ROAS', $result['error']);
        $this->assertFalse($this->posted());
    }

    public function test_accelerated_pacing_needs_a_bid_cap(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '2500', 'bid_strategy' => 'LOWEST_COST_WITHOUT_CAP']);

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'pacing_type' => 'no_pacing']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('bid cap', $result['error']);
        $this->assertFalse($this->posted());
    }

    public function test_accelerated_pacing_is_sent_with_a_bid_cap(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '2500', 'bid_strategy' => 'LOWEST_COST_WITH_BID_CAP']);

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'pacing_type' => 'no_pacing']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame(['no_pacing'], json_decode($this->postedFields()['pacing_type'], true));
    }

    public function test_dayparting_is_sent_with_day_parting_pacing_on_a_lifetime_budget(): void
    {
        $this->campaign();
        $this->fakeMeta(['lifetime_budget' => '8000']);

        $result = $this->edit([
            'entity_type' => 'ad_set',
            'id' => 'adset-1',
            'adset_schedule' => [[
                'days' => [1, 2, 3, 4, 5],
                'start_minute' => 540,
                'end_minute' => 1020,
            ]],
        ]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $schedule = json_decode($this->postedFields()['adset_schedule'], true);
        $this->assertSame([1, 2, 3, 4, 5], $schedule[0]['days']);
        $this->assertSame(540, $schedule[0]['start_minute']);
        $this->assertSame(1020, $schedule[0]['end_minute']);
        $this->assertSame(['day_parting'], json_decode($this->postedFields()['pacing_type'], true));
    }

    public function test_dayparting_is_refused_on_a_daily_budget(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '2500']);

        $result = $this->edit([
            'entity_type' => 'ad_set',
            'id' => 'adset-1',
            'adset_schedule' => [[
                'days' => [1],
                'start_minute' => 0,
                'end_minute' => 1440,
            ]],
        ]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('lifetime budget', $result['error']);
        $this->assertFalse($this->posted());
    }

    public function test_an_empty_dayparting_schedule_clears_it(): void
    {
        $this->campaign();
        $this->fakeMeta(['lifetime_budget' => '8000', 'adset_schedule' => [['days' => [1]]]]);

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'adset_schedule' => []]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('[]', $this->postedFields()['adset_schedule']);
    }

    public function test_an_audience_change_keeps_the_rest_of_the_targeting(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '2500', 'targeting' => $this->liveTargeting()]);

        $result = $this->edit([
            'entity_type' => 'ad_set',
            'id' => 'adset-1',
            'targeting' => ['age_min' => 25, 'age_max' => 54],
        ]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $targeting = json_decode($this->postedFields()['targeting'], true);
        $this->assertSame(25, $targeting['age_min']);
        $this->assertSame(54, $targeting['age_max']);
        $this->assertSame(['US'], $targeting['geo_locations']['countries']);
        $this->assertSame(['facebook', 'instagram'], $targeting['publisher_platforms']);
        $this->assertSame(['mobile'], $targeting['device_platforms']);
        $this->assertSame([1], $targeting['genders']);
        $this->assertStringContainsString('audience', $result['learning_warning'][0]);
    }

    public function test_clearing_a_gender_leaves_the_location_in_place(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '2500', 'targeting' => $this->liveTargeting()]);

        $result = $this->edit([
            'entity_type' => 'ad_set',
            'id' => 'adset-1',
            'targeting' => ['genders' => []],
        ]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $targeting = json_decode($this->postedFields()['targeting'], true);
        $this->assertArrayNotHasKey('genders', $targeting);
        $this->assertSame(['US'], $targeting['geo_locations']['countries']);
        $this->assertSame(['facebook', 'instagram'], $targeting['publisher_platforms']);
    }

    public function test_a_housing_campaign_cannot_narrow_age_set_a_gender_or_use_a_zip(): void
    {
        $this->campaign();
        $open = $this->liveTargeting();
        unset($open['genders']);
        $this->fakeMeta(
            ['daily_budget' => '2500', 'targeting' => $open],
            ['special_ad_categories' => ['HOUSING']],
        );

        $age = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'targeting' => ['age_min' => 30]]);
        $this->assertFalse($age['ok']);
        $this->assertStringContainsString('age cannot be narrowed', $age['error']);

        $gender = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'targeting' => ['genders' => [1]]]);
        $this->assertFalse($gender['ok']);
        $this->assertStringContainsString('gender cannot be set', $gender['error']);

        $zip = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'targeting' => [
            'geo_locations' => ['countries' => ['US'], 'zips' => [['key' => 'US:90210']]],
        ]]);
        $this->assertFalse($zip['ok']);
        $this->assertStringContainsString('ZIP', $zip['error']);
        $this->assertFalse($this->posted());
    }

    public function test_an_audience_edit_is_refused_when_the_current_targeting_cannot_be_read(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '2500']);

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'targeting' => ['age_min' => 25]]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('could not be read', $result['error']);
        $this->assertFalse($this->posted());
    }

    public function test_a_language_name_is_sent_as_the_locale_meta_returned(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '2500', 'targeting' => $this->liveTargeting()], [], [
            ['key' => '6', 'name' => 'English (US)'],
        ]);

        $result = $this->edit([
            'entity_type' => 'ad_set',
            'id' => 'adset-1',
            'targeting' => ['locales' => ['English (US)']],
        ]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $targeting = json_decode($this->postedFields()['targeting'], true);
        $this->assertSame([6], $targeting['locales']);
        $this->assertSame(['facebook', 'instagram'], $targeting['publisher_platforms']);
    }

    public function test_several_language_matches_are_listed_and_nothing_is_posted(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '2500', 'targeting' => $this->liveTargeting()], [], [
            ['key' => '6', 'name' => 'English (US)'],
            ['key' => '24', 'name' => 'English (UK)'],
        ]);

        $result = $this->edit([
            'entity_type' => 'ad_set',
            'id' => 'adset-1',
            'targeting' => ['locales' => ['English']],
        ]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('English (US) is 6', $result['error']);
        $this->assertStringContainsString('English (UK) is 24', $result['error']);
        $this->assertFalse($this->posted());
    }

    public function test_manual_placements_keep_the_audience_and_device(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '2500', 'targeting' => $this->liveTargeting()]);

        $result = $this->edit([
            'entity_type' => 'ad_set',
            'id' => 'adset-1',
            'targeting' => [
                'publisher_platforms' => ['facebook', 'instagram'],
                'facebook_positions' => ['feed'],
                'instagram_positions' => ['stream'],
            ],
        ]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $targeting = json_decode($this->postedFields()['targeting'], true);
        $this->assertSame(['facebook', 'instagram'], $targeting['publisher_platforms']);
        $this->assertSame(['feed'], $targeting['facebook_positions']);
        $this->assertSame(['stream'], $targeting['instagram_positions']);
        $this->assertSame(['US'], $targeting['geo_locations']['countries']);
        $this->assertSame(['mobile'], $targeting['device_platforms']);
        $this->assertStringContainsString('placements', $result['learning_warning'][0]);
    }

    public function test_advantage_placements_clear_the_manual_platforms(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '2500', 'targeting' => $this->liveTargeting()]);

        $result = $this->edit([
            'entity_type' => 'ad_set',
            'id' => 'adset-1',
            'targeting' => ['advantage_placements' => true],
        ]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $targeting = json_decode($this->postedFields()['targeting'], true);
        $this->assertArrayNotHasKey('publisher_platforms', $targeting);
        $this->assertArrayNotHasKey('advantage_placements', $targeting);
        $this->assertSame(['US'], $targeting['geo_locations']['countries']);
        $this->assertSame(['mobile'], $targeting['device_platforms']);
    }

    public function test_threads_also_includes_the_instagram_feed(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '2500', 'targeting' => $this->liveTargeting()]);

        $result = $this->edit([
            'entity_type' => 'ad_set',
            'id' => 'adset-1',
            'targeting' => [
                'publisher_platforms' => ['threads'],
                'threads_positions' => ['threads_stream'],
            ],
        ]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $targeting = json_decode($this->postedFields()['targeting'], true);
        $this->assertContains('threads', $targeting['publisher_platforms']);
        $this->assertContains('instagram', $targeting['publisher_platforms']);
        $this->assertContains('stream', $targeting['instagram_positions']);
        $this->assertSame(['threads_stream'], $targeting['threads_positions']);
    }

    public function test_a_retired_placement_is_refused(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '2500', 'targeting' => $this->liveTargeting()]);

        $result = $this->edit([
            'entity_type' => 'ad_set',
            'id' => 'adset-1',
            'targeting' => ['facebook_positions' => ['explore']],
        ]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('explore', $result['error']);
        $this->assertFalse($this->posted());
    }

    public function test_a_device_change_keeps_the_audience_and_placements(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '2500', 'targeting' => $this->liveTargeting()]);

        $result = $this->edit([
            'entity_type' => 'ad_set',
            'id' => 'adset-1',
            'targeting' => [
                'device_platforms' => ['mobile'],
                'user_os' => ['iOS_ver_14.0_and_above'],
                'user_device' => ['iPhone'],
                'wireless_carrier' => ['Wi-Fi'],
            ],
        ]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $targeting = json_decode($this->postedFields()['targeting'], true);
        $this->assertSame(['mobile'], $targeting['device_platforms']);
        $this->assertSame(['iOS_ver_14.0_and_above'], $targeting['user_os']);
        $this->assertSame(['iPhone'], $targeting['user_device']);
        $this->assertSame(['Wifi'], $targeting['wireless_carrier']);
        $this->assertSame(['US'], $targeting['geo_locations']['countries']);
        $this->assertSame(['facebook', 'instagram'], $targeting['publisher_platforms']);
        $this->assertStringContainsString('device', $result['learning_warning'][0]);
    }

    public function test_desktop_only_cannot_keep_a_mobile_device_limit(): void
    {
        $this->campaign();
        $targeting = $this->liveTargeting();
        $targeting['user_os'] = ['iOS'];
        $this->fakeMeta(['daily_budget' => '2500', 'targeting' => $targeting]);

        $result = $this->edit([
            'entity_type' => 'ad_set',
            'id' => 'adset-1',
            'targeting' => ['device_platforms' => ['desktop']],
        ]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('mobile', $result['error']);
        $this->assertFalse($this->posted());
    }

    public function test_a_conversion_event_keeps_the_pixel(): void
    {
        $this->campaign();
        $this->fakeMeta([
            'daily_budget' => '2500',
            'promoted_object' => ['pixel_id' => '111', 'custom_event_type' => 'LEAD', 'custom_conversion_id' => '999'],
        ]);

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'conversion_event' => 'Purchase']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $promoted = json_decode($this->postedFields()['promoted_object'], true);
        $this->assertSame('111', $promoted['pixel_id']);
        $this->assertSame('PURCHASE', $promoted['custom_event_type']);
        $this->assertArrayNotHasKey('custom_conversion_id', $promoted);
        $this->assertStringContainsString('optimization', $result['learning_warning'][0]);
    }

    public function test_page_view_cannot_be_the_conversion_event(): void
    {
        $this->campaign();
        $this->fakeMeta([
            'daily_budget' => '2500',
            'promoted_object' => ['pixel_id' => '111', 'custom_event_type' => 'LEAD'],
        ]);

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'conversion_event' => 'PAGE_VIEW']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('PAGE_VIEW', $result['error']);
        $this->assertFalse($this->posted());
    }

    public function test_a_frequency_cap_is_only_for_reach(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '2500', 'optimization_goal' => 'REACH']);

        $saved = $this->edit([
            'entity_type' => 'ad_set',
            'id' => 'adset-1',
            'frequency_control_specs' => [[
                'event' => 'IMPRESSIONS',
                'interval_days' => 7,
                'max_frequency' => 2,
            ]],
        ]);

        $this->assertTrue($saved['ok'], $saved['error'] ?? '');
        $this->assertSame([[
            'event' => 'IMPRESSIONS',
            'interval_days' => 7,
            'max_frequency' => 2,
        ]], json_decode($this->postedFields()['frequency_control_specs'], true));
    }

    public function test_a_frequency_cap_is_refused_unless_the_ad_set_optimizes_for_reach(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '2500', 'optimization_goal' => 'OFFSITE_CONVERSIONS']);

        $result = $this->edit([
            'entity_type' => 'ad_set',
            'id' => 'adset-1',
            'frequency_control_specs' => [[
                'event' => 'IMPRESSIONS',
                'interval_days' => 7,
                'max_frequency' => 2,
            ]],
        ]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('reach', $result['error']);
        $this->assertFalse($this->posted());
    }

    public function test_a_value_rule_needs_highest_volume_or_cost_cap(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '2500', 'bid_strategy' => 'LOWEST_COST_WITHOUT_CAP']);

        $saved = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'value_rule_set_id' => '445566']);

        $this->assertTrue($saved['ok'], $saved['error'] ?? '');
        $this->assertSame('445566', $this->postedFields()['value_rule_set_id']);
        $this->assertSame('true', $this->postedFields()['value_rules_applied']);
    }

    public function test_a_value_rule_is_refused_with_a_bid_cap(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '2500', 'bid_strategy' => 'LOWEST_COST_WITH_BID_CAP']);

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'value_rule_set_id' => '445566']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('cost cap', $result['error']);
        $this->assertFalse($this->posted());
    }

    public function test_a_value_rule_can_be_detached(): void
    {
        $this->campaign();
        $this->fakeMeta(['daily_budget' => '2500', 'bid_strategy' => 'COST_CAP']);

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'value_rules_applied' => false]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('false', $this->postedFields()['value_rules_applied']);
        $this->assertArrayNotHasKey('value_rule_set_id', $this->postedFields());
    }

    public function test_a_cost_goal_is_sent_with_the_live_strategy_and_confirmed(): void
    {
        $this->campaign();
        $reads = 0;

        Http::fake(function (HttpRequest $request) use (&$reads) {
            $path = parse_url($request->url(), PHP_URL_PATH) ?? '';

            if ($request->method() === 'GET' && str_ends_with($path, '/adsets')) {
                return Http::response(['data' => [['id' => 'adset-1', 'name' => 'Winter ad set']]]);
            }

            if ($request->method() === 'GET' && str_ends_with($path, '/adset-1')) {
                $reads++;

                return Http::response([
                    'id' => 'adset-1',
                    'name' => 'Winter ad set',
                    'bid_strategy' => 'COST_CAP',
                    'bid_amount' => $reads >= 3 ? '200' : '100',
                    'daily_budget' => '2500',
                ]);
            }

            if ($request->method() === 'GET' && str_ends_with($path, '/120252047635070626')) {
                return Http::response(['id' => '120252047635070626']);
            }

            return Http::response(['success' => true]);
        });

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'bid_amount' => 2]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('COST_CAP', $this->postedFields()['bid_strategy']);
        $this->assertSame(200, $this->postedFields()['bid_amount']);
        $this->assertSame(2, $result['confirmed_bid_amount']);
    }

    public function test_a_cost_goal_is_not_reported_when_meta_keeps_the_old_amount(): void
    {
        $this->campaign();
        $this->fakeMeta([
            'daily_budget' => '2500',
            'bid_strategy' => 'COST_CAP',
            'bid_amount' => '100',
        ]);

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'bid_amount' => 2]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('left the cost per result goal at 1 USD', $result['error']);
        $this->assertSame('COST_CAP', $this->postedFields()['bid_strategy']);
        $this->assertSame(200, $this->postedFields()['bid_amount']);
    }

    public function test_a_successful_ad_set_edit_clears_the_stored_campaign_error(): void
    {
        $campaign = $this->campaign();
        $campaign->update([
            'last_error' => '(#100) Param bid_amount must be a number greater than or equal to 1 [OAuthException 100] on adset-1',
        ]);
        $this->fakeMeta([
            'daily_budget' => '2500',
            'name' => 'Winter ad set',
        ]);

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'name' => 'Winter ad set renamed']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertNull($campaign->fresh()->last_error);
    }

    public function test_highest_volume_clears_the_stored_bid_amount_and_is_confirmed(): void
    {
        $this->campaign();
        $reads = 0;

        Http::fake(function (HttpRequest $request) use (&$reads) {
            $path = parse_url($request->url(), PHP_URL_PATH) ?? '';

            if ($request->method() === 'GET' && str_ends_with($path, '/adsets')) {
                return Http::response(['data' => [['id' => 'adset-1', 'name' => 'Winter ad set']]]);
            }

            if ($request->method() === 'GET' && str_ends_with($path, '/adset-1')) {
                $reads++;

                return Http::response([
                    'id' => 'adset-1',
                    'bid_strategy' => $reads >= 2 ? 'LOWEST_COST_WITHOUT_CAP' : 'COST_CAP',
                    'bid_amount' => '200',
                    'daily_budget' => '2500',
                ]);
            }

            if ($request->method() === 'GET' && str_ends_with($path, '/120252047635070626')) {
                return Http::response(['id' => '120252047635070626']);
            }

            return Http::response(['success' => true]);
        });

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'bid_strategy' => 'LOWEST_COST_WITHOUT_CAP']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('LOWEST_COST_WITHOUT_CAP', $this->postedFields()['bid_strategy']);
        $this->assertSame('', $this->postedFields()['bid_amount']);
        $this->assertArrayNotHasKey('confirmed_bid_amount', $result);
        $this->assertStringContainsString('Highest volume', $result['note']);
    }

    public function test_highest_volume_sends_the_cleared_bid_amount_once(): void
    {
        $this->campaign();
        $this->fakeMeta([
            'daily_budget' => '2500',
            'bid_strategy' => 'COST_CAP',
            'bid_amount' => '200',
        ]);

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'bid_strategy' => 'LOWEST_COST_WITHOUT_CAP']);

        $posted = [];

        foreach (Http::recorded() as [$request]) {
            if ($request->method() === 'POST' && str_ends_with((string) parse_url($request->url(), PHP_URL_PATH), '/adset-1')) {
                $posted[] = $request->data();
            }
        }

        $this->assertFalse($result['ok']);
        $this->assertCount(1, $posted);
        $this->assertSame('LOWEST_COST_WITHOUT_CAP', $posted[0]['bid_strategy']);
        $this->assertSame('', $posted[0]['bid_amount']);
    }

    public function test_highest_volume_is_not_reported_when_meta_keeps_the_cost_cap(): void
    {
        $this->campaign();
        $this->fakeMeta([
            'daily_budget' => '2500',
            'bid_strategy' => 'COST_CAP',
            'bid_amount' => '200',
        ]);

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'bid_strategy' => 'LOWEST_COST_WITHOUT_CAP']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('left the bid strategy as COST_CAP', $result['error']);
        $this->assertSame('LOWEST_COST_WITHOUT_CAP', $this->postedFields()['bid_strategy']);
        $this->assertSame('', $this->postedFields()['bid_amount']);
    }

    public function test_an_ad_set_can_be_edited_by_its_name(): void
    {
        $this->campaign();

        Http::fake(function (HttpRequest $request) {
            $path = parse_url($request->url(), PHP_URL_PATH) ?? '';

            if ($request->method() === 'GET' && str_ends_with($path, '/adsets')) {
                return Http::response(['data' => [['id' => 'adset-1', 'name' => 'Winter ad set']]]);
            }

            if ($request->method() === 'GET' && str_ends_with($path, '/adset-1')) {
                return Http::response(['id' => 'adset-1', 'name' => 'Winter ad set', 'daily_budget' => '2500']);
            }

            if ($request->method() === 'GET' && str_ends_with($path, '/120252047635070626')) {
                return Http::response(['id' => '120252047635070626']);
            }

            return Http::response(['success' => true]);
        });

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'Winter ad set', 'budget' => 40]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('adset-1', $result['id']);
        $this->assertSame(4000, $this->postedFields()['daily_budget']);
    }

    public function test_a_name_that_matches_two_ad_sets_changes_nothing(): void
    {
        $this->campaign();

        Http::fake(function (HttpRequest $request) {
            $path = parse_url($request->url(), PHP_URL_PATH) ?? '';

            if ($request->method() === 'GET' && str_ends_with($path, '/adsets')) {
                return Http::response(['data' => [
                    ['id' => 'adset-1', 'name' => 'Winter ad set'],
                    ['id' => 'adset-2', 'name' => 'Winter ad set'],
                ]]);
            }

            return Http::response(['success' => true]);
        });

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'Winter ad set', 'budget' => 40]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('adset-1', $result['error']);
        $this->assertStringContainsString('adset-2', $result['error']);
        $this->assertFalse($this->posted());
    }

    public function test_the_approval_names_the_ad_set_and_the_cost_goal(): void
    {
        $this->campaign();

        Http::fake(function (HttpRequest $request) {
            $path = parse_url($request->url(), PHP_URL_PATH) ?? '';

            if ($request->method() === 'GET' && str_ends_with($path, '/adsets')) {
                return Http::response(['data' => [['id' => 'adset-1', 'name' => 'Winter ad set']]]);
            }

            if ($request->method() === 'GET' && str_ends_with($path, '/adset-1')) {
                return Http::response([
                    'id' => 'adset-1',
                    'bid_strategy' => 'COST_CAP',
                    'bid_amount' => '100',
                    'daily_budget' => '2500',
                ]);
            }

            if ($request->method() === 'GET' && str_ends_with($path, '/120252047635070626')) {
                return Http::response(['id' => '120252047635070626']);
            }

            return Http::response(['success' => true]);
        });

        $approval = $this->tool()->shouldRequestApproval(new Request([
            'entity_type' => 'ad_set',
            'id' => 'Winter ad set',
            'bid_amount' => 2,
        ], 'call-guard-bid'));

        $this->assertNotNull($approval);
        $this->assertStringContainsString('Winter ad set (adset-1)', (string) $approval->reason);
        $this->assertStringContainsString('Cost per result goal 2 USD', (string) $approval->reason);
    }

    /** @return array<string, mixed> */
    private function liveTargeting(): array
    {
        return [
            'geo_locations' => ['countries' => ['US'], 'location_types' => ['home']],
            'age_min' => 18,
            'age_max' => 65,
            'genders' => [1],
            'publisher_platforms' => ['facebook', 'instagram'],
            'device_platforms' => ['mobile'],
            'targeting_automation' => ['advantage_audience' => 0],
        ];
    }
}
