<?php

namespace Tests\Feature;

use App\Agent\Choices;
use App\Agent\Tools\Campaign\SetTargeting;
use App\Agent\Workspace;
use App\Campaigns\Platforms\Platforms;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Ai\Tools\Request;
use Tests\TestCase;

/**
 * "I started with display and it was building for search, and later it
 * switched to display after generating headlines and descriptions."
 *
 * Read from his conversation. He chose Display, and two steps later the
 * placements question offered him Search:
 *
 *   assistant  Choose the Display placements on screen.
 *   user       Run on search    (Already recorded: placements: search)
 *
 * So a Display campaign carried the Search network, and the copy step read the
 * network rather than the campaign type and wrote a responsive search ad. He
 * was then asked, mid flow, to choose a format: "the copy was built as a
 * Search responsive ad, but the campaign type is Display."
 *
 * The networks a Google campaign can run on are decided by its channel.
 * placementsFor() only ever filtered by objective, so every objective except
 * awareness offered all three networks whatever was being built.
 *
 * A Display campaign runs on the Display network and nothing else. A Search
 * campaign keeps all three, because display there is Google's own Display
 * Network expansion and the publisher already sends it - narrowing Search as
 * well would have taken a working feature away.
 */
class ADisplayCampaignIsNotOfferedSearchNetworksTest extends TestCase
{
    use RefreshDatabase;

    private function campaign(string $type, string $objective = 'SALES'): Campaign
    {
        $user = User::factory()->create();
        $this->actingAs($user);

        $campaign = Campaign::create([
            'user_id' => $user->getKey(),
            'name' => 'Networks',
            'platform' => 'google',
            'campaign_type' => $type,
            'status' => 'draft',
            'ad_account_id' => '2099157735',
            'objective' => $objective,
            'landing_url' => 'https://stockprices.com/landing',
        ]);

        app(Workspace::class)->bindTo('networks-'.$type);
        app(Workspace::class)->focusOn($campaign);

        return $campaign;
    }

    /** @return list<string> what the placements question put on screen */
    private function offered(Campaign $campaign): array
    {
        app(SetTargeting::class)->handle(new Request(['section' => 'placements']));

        $offer = collect(app(Choices::class)->drain())->firstWhere('field', 'placements');

        return array_column($offer['options'] ?? [], 'value');
    }

    /** The defect in one assertion. */
    public function test_a_display_campaign_is_not_offered_the_search_network(): void
    {
        $this->assertSame(['display'], $this->offered($this->campaign('display')));
    }

    /**
     * Search keeps all three, including display.
     *
     * Display on a Search campaign is Google's Display Network expansion -
     * targetContentNetwork on a SEARCH channel - which the publisher already
     * sends. The first version of this fix narrowed Search to its two search
     * networks and would have removed that; PlacementsMatchThePlatformTest
     * caught it.
     */
    public function test_a_search_campaign_keeps_the_display_network_too(): void
    {
        $this->assertSame(
            ['search', 'search_partners', 'display'],
            $this->offered($this->campaign('search')),
        );
    }

    /** Whatever the objective: the channel decides, not the goal. */
    public function test_the_objective_does_not_widen_the_networks(): void
    {
        foreach (['SALES', 'LEADS', 'WEBSITE_TRAFFIC', 'BRAND_AWARENESS_AND_REACH'] as $objective) {
            $this->assertSame(
                ['display'],
                $this->offered($this->campaign('display', $objective)),
                'a display campaign was offered more than the display network for '.$objective,
            );
        }
    }

    /** And a network from the wrong channel cannot be saved even if asked for. */
    public function test_saving_the_search_network_on_a_display_campaign_is_refused(): void
    {
        $campaign = $this->campaign('display');

        $result = json_decode((string) app(SetTargeting::class)->handle(new Request([
            'placements' => ['search'],
        ])), true);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('search', $result['error']);
        $this->assertSame([], (array) $campaign->fresh()->placements);
    }

    /** The rule is the platform's to state, and it needs the campaign to state it. */
    public function test_the_rule_is_asked_of_the_channel(): void
    {
        $rules = app(Platforms::class)->for('google');

        $this->assertSame(['search', 'search_partners', 'display'], $rules->placementsFor('SALES', 'search'));
        $this->assertSame(['display'], $rules->placementsFor('SALES', 'display'));
        $this->assertSame(['display'], $rules->placementsFor('BRAND_AWARENESS_AND_REACH', 'display'));
    }

    /**
     * Performance Max decides its own networks.
     *
     * Google runs it across everything it owns and gives no network choice, so
     * offering one would be a question with no answer.
     */
    public function test_performance_max_is_not_asked_about_networks(): void
    {
        $this->assertSame([], $this->offered($this->campaign('performance_max')));
    }
}
