<?php

namespace Tests\Feature;

use App\Agent\NamespacedTool;
use App\Agent\Tools\Campaign\EditGoogleDeviceAdjustments;
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 GoogleChatDeviceAdjustmentsTest extends TestCase
{
    use RefreshDatabase;

    private array $criteria;

    private string $strategy = 'MANUAL_CPC';

    private ?float $targetCpa = null;

    private bool $ignoreUpdate = 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-device-adjustments');
        $workspace->ownedBy($user);
        $campaign = Campaign::create([
            'user_id' => $user->id, 'name' => 'Search', 'platform' => 'google',
            'status' => 'published', 'ad_account_id' => '1234567890', 'external_campaign_id' => '101',
        ]);
        $workspace->produced($campaign);
        $workspace->focusOn($campaign);
        $this->criteria = [
            ['resourceName' => 'customers/1234567890/campaignCriteria/101~1', 'type' => 'DEVICE', 'status' => 'ENABLED', 'bidModifier' => 1.0, 'device' => ['type' => 'MOBILE']],
            ['resourceName' => 'customers/1234567890/campaignCriteria/101~2', 'type' => 'DEVICE', 'status' => 'ENABLED', 'bidModifier' => 1.2, 'device' => ['type' => 'DESKTOP']],
            ['resourceName' => 'customers/1234567890/campaignCriteria/101~3', 'type' => 'DEVICE', 'status' => 'ENABLED', 'bidModifier' => 1.0, 'device' => ['type' => 'TABLET']],
            ['resourceName' => 'customers/1234567890/campaignCriteria/101~4', 'type' => 'LOCATION', 'status' => 'ENABLED', 'location' => ['geoTargetConstant' => 'geoTargetConstants/2840']],
        ];
        $google = Mockery::mock(GoogleAdsService::class)->makePartial();
        $google->shouldReceive('readCampaignProfile')->andReturnUsing(fn (): array => [
            'id' => '101', 'advertising_channel_type' => 'SEARCH', 'profile_fields_error' => null,
            'bidding_strategy_type' => $this->strategy, 'bidding_portfolio' => '', 'target_cpa' => $this->targetCpa,
        ]);
        $google->shouldReceive('readManagerCriteria')->andReturnUsing(fn (): array => $this->criteria);
        $google->shouldReceive('updateManagerCriteria')->andReturnUsing(function ($connection, string $id, array $before, array $patch): void {
            $this->assertSame('101', $id);
            $this->assertSame($this->criteria, $before);
            if ($this->ignoreUpdate) {
                return;
            }
            foreach ($this->criteria as &$criterion) {
                if ($criterion['type'] === 'DEVICE') {
                    $criterion['bidModifier'] = $patch['device_bid_adjustments'][$criterion['device']['type']];
                }
            }
            unset($criterion);
        });
        $this->app->instance(GoogleAdsService::class, $google);
    }

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

    private function request(array $changes, string $id): Request
    {
        return new Request(['campaign_id' => '101', 'device_bid_adjustments' => $changes], $id);
    }

    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_unrequested_devices_and_targeting(): void
    {
        $request = $this->request(['DESKTOP' => 0, 'TABLET' => 0], 'device');
        $this->assertNotNull($this->tool()->shouldRequestApproval($request));
        $result = $this->edit($request);
        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertEquals(1.0, $result['after']['MOBILE']);
        $this->assertEquals(0.0, $result['after']['DESKTOP']);
        $this->assertEquals(0.0, $result['after']['TABLET']);
        $this->assertSame('LOCATION', $this->criteria[3]['type']);
        $this->assertSame('applied', CampaignChange::sole()->state);
    }

    public function test_stale_approval_does_not_write(): void
    {
        $request = $this->request(['DESKTOP' => 0], 'stale');
        $this->assertNotNull($this->tool()->shouldRequestApproval($request));
        $this->criteria[0]['bidModifier'] = 1.1;
        $this->assertFalse($this->edit($request)['ok']);
        $this->assertDatabaseCount('campaign_changes', 0);
    }

    public function test_omitted_modifier_is_neutral_and_explicit_zero_stays_excluded(): void
    {
        unset($this->criteria[0]['bidModifier']);
        $this->criteria[2]['bidModifier'] = 0.0;
        $request = $this->request(['MOBILE' => 1.2], 'neutral');
        $this->assertNotNull($this->tool()->shouldRequestApproval($request));
        $result = $this->edit($request);
        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame(1, $result['before']['MOBILE']);
        $this->assertSame(0, $result['after']['TABLET']);
    }

    public function test_mobile_only_excludes_desktop_and_tablet_together_with_omitted_neutral_modifiers(): void
    {
        foreach ([0, 1, 2] as $index) {
            unset($this->criteria[$index]['bidModifier']);
        }
        $request = $this->request(['DESKTOP' => 0, 'TABLET' => 0], 'mobile-only');
        $this->assertNotNull($this->tool()->shouldRequestApproval($request));

        $result = $this->edit($request);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertEquals(['MOBILE' => 1, 'DESKTOP' => 0, 'TABLET' => 0], $result['after']);
        $this->assertSame('LOCATION', $this->criteria[3]['type']);
        $this->assertSame('applied', CampaignChange::sole()->state);
    }

    public function test_target_cpa_adjustments_disclose_the_target_change(): void
    {
        $this->strategy = 'TARGET_CPA';
        $request = $this->request(['MOBILE' => 1.5], 'target-cpa');
        $approval = $this->tool()->shouldRequestApproval($request);
        $this->assertNotNull($approval);
        $this->assertStringContainsString('CPA target', json_encode($approval));
        $result = $this->edit($request);
        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertStringContainsString('CPA target', $result['note']);
        $this->assertEquals(1.5, $result['after']['MOBILE']);
    }

    public function test_maximize_conversions_with_target_cpa_supports_device_target_adjustments(): void
    {
        $this->strategy = 'MAXIMIZE_CONVERSIONS';
        $this->targetCpa = 10.0;
        $request = $this->request(['MOBILE' => 0.8], 'maximize-target-cpa');
        $this->assertNotNull($this->tool()->shouldRequestApproval($request));
        $this->assertTrue($this->edit($request)['ok']);
    }

    public function test_missing_device_and_unsupported_strategy_are_refused(): void
    {
        $this->assertNull($this->tool()->shouldRequestApproval($this->request(['CONNECTED_TV' => 0], 'missing')));
        $this->strategy = 'UNKNOWN';
        $this->assertFalse($this->edit($this->request(['DESKTOP' => 0], 'strategy'))['ok']);
        $this->assertDatabaseCount('campaign_changes', 0);
    }

    public function test_smart_bidding_allows_device_exclusion_but_not_regular_adjustments(): void
    {
        $this->strategy = 'MAXIMIZE_CONVERSIONS';
        $this->criteria[1]['bidModifier'] = 1.0;
        $request = $this->request(['DESKTOP' => 0], 'smart-exclusion');
        $this->assertNotNull($this->tool()->shouldRequestApproval($request));
        $this->assertTrue($this->edit($request)['ok']);
        $this->assertNull($this->tool()->shouldRequestApproval($this->request(['TABLET' => 1.2], 'smart-adjustment')));
    }

    public function test_unconfirmed_write_requires_reconciliation(): void
    {
        $this->ignoreUpdate = true;
        $request = $this->request(['DESKTOP' => 0], 'unconfirmed');
        $this->assertNotNull($this->tool()->shouldRequestApproval($request));
        $result = $this->edit($request);
        $this->assertFalse($result['ok']);
        $this->assertTrue($result['reconciliation_required']);
        $this->assertSame('failed', CampaignChange::sole()->state);
    }
}
