<?php

namespace Tests\Feature;

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

    private array $criteria = [];

    private bool $ignoreUpdate = false;

    private string $zone = 'America/Phoenix';

    private Campaign $campaign;

    private bool $retargetDuringUpdate = 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-delivery-schedule');
        $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',
        ]);
        $workspace->produced($this->campaign);
        $workspace->focusOn($this->campaign);
        $this->criteria = [[
            'resourceName' => 'customers/1234567890/campaignCriteria/101~55',
            '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', 'time_zone' => $this->zone,
            'profile_fields_error' => null,
        ]);
        $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);
            $this->assertSame(['delivery_schedule'], array_keys($patch));
            if ($this->ignoreUpdate) {
                return;
            }
            $this->criteria = array_values(array_filter($this->criteria, fn (array $row): bool => $row['type'] !== 'AD_SCHEDULE'));
            foreach ($patch['delivery_schedule'] as $i => $schedule) {
                $this->criteria[] = [
                    'resourceName' => 'customers/1234567890/campaignCriteria/101~'.(100 + $i),
                    'type' => 'AD_SCHEDULE', 'status' => 'ENABLED', 'adSchedule' => $schedule,
                ];
            }
            if ($this->retargetDuringUpdate) {
                $this->campaign->update(['ad_account_id' => '9876543210']);
            }
        });
        $this->app->instance(GoogleAdsService::class, $google);
    }

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

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

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

    private function window(string $day = 'MONDAY'): array
    {
        return ['dayOfWeek' => $day, 'startHour' => 10, 'startMinute' => 'ZERO', 'endHour' => 20, 'endMinute' => 'ZERO'];
    }

    public function test_schedule_is_approved_verified_and_preserves_other_targeting(): void
    {
        $request = $this->request([$this->window(), $this->window('TUESDAY')], 'schedule');
        $this->assertNotNull($this->tool()->shouldRequestApproval($request));
        $result = $this->edit($request);
        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('America/Phoenix', $result['time_zone']);
        $this->assertTrue($result['verified']);
        $this->assertSame('LOCATION', $this->criteria[0]['type']);
        $this->assertSame('applied', CampaignChange::sole()->state);
        $this->assertFalse($this->edit($request)['ok']);

        $clear = $this->request([], 'clear');
        $this->assertNotNull($this->tool()->shouldRequestApproval($clear));
        $this->assertTrue($this->edit($clear)['ok']);
        $this->assertCount(1, $this->criteria);
    }

    public function test_stale_approval_or_timezone_is_refused(): void
    {
        $request = $this->request([$this->window()], 'stale');
        $this->assertNotNull($this->tool()->shouldRequestApproval($request));
        $this->zone = 'America/New_York';
        $this->assertFalse($this->edit($request)['ok']);
        $this->assertDatabaseCount('campaign_changes', 0);
    }

    public function test_overlapping_windows_and_existing_schedule_adjustments_are_refused(): void
    {
        $request = $this->request([$this->window(), $this->window()], 'overlap');
        $this->assertNull($this->tool()->shouldRequestApproval($request));
        $this->assertFalse($this->edit($request)['ok']);
        $this->criteria[] = [
            'resourceName' => 'customers/1234567890/campaignCriteria/101~99',
            'type' => 'AD_SCHEDULE', 'status' => 'ENABLED', 'bidModifier' => 1.2, 'adSchedule' => $this->window(),
        ];
        $this->assertFalse($this->edit($this->request([], 'modifier'))['ok']);
        $this->assertDatabaseCount('campaign_changes', 0);
    }

    public function test_unconfirmed_write_requires_reconciliation(): void
    {
        $this->ignoreUpdate = true;
        $request = $this->request([$this->window()], '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);
    }

    public function test_campaign_retargeted_during_write_requires_reconciliation(): void
    {
        $this->retargetDuringUpdate = true;
        $request = $this->request([$this->window()], 'retargeted');
        $this->assertNotNull($this->tool()->shouldRequestApproval($request));
        $result = $this->edit($request);
        $this->assertFalse($result['ok']);
        $this->assertTrue($result['reconciliation_required']);
    }
}
