<?php

namespace Tests\Feature;

use App\Agent\NamespacedTool;
use App\Agent\Tools\Campaign\EditGoogleCampaignNetworks;
use App\Agent\Workspace;
use App\Models\Campaign;
use App\Models\CampaignChange;
use App\Models\User;
use App\Services\GoogleAdsService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Ai\Tools\Request;
use Mockery;
use Tests\TestCase;

class GoogleChatCampaignNetworksTest extends TestCase
{
    use RefreshDatabase;

    private Campaign $campaign;

    private array $networks = [
        'targetGoogleSearch' => true,
        'targetSearchNetwork' => false,
        'targetContentNetwork' => false,
        'targetPartnerSearchNetwork' => false,
    ];

    private bool $ignoreUpdate = false;

    private bool $changeLocalDuringUpdate = false;

    private bool $changeCampaignDuringUpdate = false;

    protected function setUp(): void
    {
        parent::setUp();
        config([
            'platforms.guardrails.allowed_ad_accounts' => ['google:*'],
            'platforms.guardrails.paused' => false,
            'platforms.guardrails.dry_run' => false,
            'platforms.guardrails.change_cooldown_seconds' => 0,
            'platforms.guardrails.max_changes_per_day' => 100,
            'services.google_ads.refresh_token' => 'refresh-token',
            'services.google_ads.customer_id' => '1234567890',
        ]);
        $user = User::factory()->create();
        $this->actingAs($user);
        $workspace = app(Workspace::class);
        $workspace->bindTo('google-campaign-networks');
        $workspace->ownedBy($user);
        $this->campaign = Campaign::create([
            'user_id' => $user->id, 'name' => 'Search', 'platform' => 'google',
            'status' => 'published', 'ad_account_id' => '1234567890', 'external_campaign_id' => '101',
            'placements' => ['search'], 'published_state' => ['placements' => ['search'], 'name' => 'Original'],
        ]);
        $workspace->produced($this->campaign);
        $workspace->focusOn($this->campaign);

        $google = Mockery::mock(GoogleAdsService::class)->makePartial();
        $google->shouldReceive('readCampaignProfile')->andReturnUsing(fn (): array => [
            'id' => '101', 'advertising_channel_type' => 'SEARCH', 'profile_fields_error' => null,
            'network_settings' => $this->networks,
        ]);
        $google->shouldReceive('updateLiveCampaign')->andReturnUsing(function ($connection, string $id, array $fields): void {
            $this->assertSame('101', $id);
            $this->assertSame(['networkSettings'], array_keys($fields));
            if (! $this->ignoreUpdate) {
                $this->networks = [...$this->networks, ...$fields['networkSettings']];
            }
            if ($this->changeLocalDuringUpdate) {
                $this->campaign->primaryAdSet->update(['placements' => ['search', 'display']]);
            }
            if ($this->changeCampaignDuringUpdate) {
                $this->campaign->update(['external_campaign_id' => '102']);
            }
        });
        $this->app->instance(GoogleAdsService::class, $google);
    }

    private function tool(): NamespacedTool
    {
        return new NamespacedTool('campaign', app(EditGoogleCampaignNetworks::class));
    }

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

    public function test_approved_edit_preserves_other_flags_and_synchronizes_only_networks(): void
    {
        $request = new Request(['campaign_id' => '101', 'network_settings' => ['targetSearchNetwork' => true]], 'network');
        $this->assertNotNull($this->tool()->shouldRequestApproval($request));
        $result = $this->edit($request);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertTrue($result['verified']);
        $this->assertTrue($this->networks['targetSearchNetwork']);
        $this->assertFalse($this->networks['targetContentNetwork']);
        $campaign = $this->campaign->fresh();
        $this->assertSame(['search', 'search_partners'], $campaign->placements);
        $this->assertSame(['search', 'search_partners'], $campaign->published_state['placements']);
        $this->assertSame('Original', $campaign->published_state['name']);
        $this->assertSame('applied', CampaignChange::sole()->state);
        $this->assertFalse($this->edit($request)['ok']);

        $restore = new Request(['campaign_id' => '101', 'network_settings' => ['targetSearchNetwork' => false]], 'restore');
        $this->assertNotNull($this->tool()->shouldRequestApproval($restore));
        $this->assertTrue($this->edit($restore)['ok']);
        $this->assertFalse($this->networks['targetSearchNetwork']);
        $this->assertSame(['search'], $this->campaign->fresh()->placements);
        $this->assertSame(['search'], $this->campaign->fresh()->published_state['placements']);
    }

    public function test_stale_changed_and_unapproved_requests_do_not_write(): void
    {
        $request = new Request(['campaign_id' => '101', 'network_settings' => ['targetSearchNetwork' => true]], 'stale');
        $this->tool()->shouldRequestApproval($request);
        $this->networks['targetContentNetwork'] = true;
        $this->assertFalse($this->edit($request)['ok']);
        $this->networks['targetContentNetwork'] = false;
        $changed = new Request(['campaign_id' => '101', 'network_settings' => ['targetContentNetwork' => true]], 'stale');
        $this->assertFalse($this->edit($changed)['ok']);
        $this->assertFalse($this->edit(new Request($request->all()))['ok']);
        $this->assertDatabaseCount('campaign_changes', 0);
    }

    public function test_incomplete_or_divergent_saved_networks_are_refused(): void
    {
        $request = new Request(['campaign_id' => '101', 'network_settings' => ['targetSearchNetwork' => true]], 'incomplete');
        unset($this->networks['targetContentNetwork']);
        $this->assertNull($this->tool()->shouldRequestApproval($request));
        $this->assertFalse($this->edit($request)['ok']);
        $this->networks['targetContentNetwork'] = false;
        $this->campaign->primaryAdSet->update(['placements' => ['search', 'display']]);
        $this->assertFalse($this->edit($request)['ok']);
        $this->assertDatabaseCount('campaign_changes', 0);
    }

    public function test_unconfirmed_write_requires_reconciliation(): void
    {
        $this->ignoreUpdate = true;
        $request = new Request(['campaign_id' => '101', 'network_settings' => ['targetSearchNetwork' => true]], 'unconfirmed');
        $this->tool()->shouldRequestApproval($request);
        $result = $this->edit($request);

        $this->assertFalse($result['ok']);
        $this->assertTrue($result['reconciliation_required']);
        $this->assertSame(['search'], $this->campaign->fresh()->placements);
        $this->assertSame('failed', CampaignChange::sole()->state);
    }

    public function test_local_change_during_platform_write_is_not_overwritten(): void
    {
        $this->changeLocalDuringUpdate = true;
        $request = new Request(['campaign_id' => '101', 'network_settings' => ['targetSearchNetwork' => true]], 'concurrent');
        $this->tool()->shouldRequestApproval($request);
        $result = $this->edit($request);

        $this->assertFalse($result['ok']);
        $this->assertTrue($result['reconciliation_required']);
        $this->assertSame(['search', 'display'], $this->campaign->fresh()->placements);
        $this->assertSame(['search'], $this->campaign->fresh()->published_state['placements']);
    }

    public function test_campaign_retargeted_during_write_is_not_synchronized(): void
    {
        $this->changeCampaignDuringUpdate = true;
        $request = new Request(['campaign_id' => '101', 'network_settings' => ['targetSearchNetwork' => true]], 'retargeted');
        $this->tool()->shouldRequestApproval($request);
        $result = $this->edit($request);

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