<?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\Database\Schema\Blueprint;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Schema;
use Laravel\Ai\Tools\Request as ToolRequest;
use Tests\TestCase;

/**
 * Spend, bid, and budget can be read for campaigns that are active or paused.
 *
 * A paused campaign still has a budget and still has the money it spent before
 * it was paused. The campaign list names objects and leaves both off, so a
 * buyer asking what a paused campaign spent was sent to Ads Manager.
 */
class DeliveryCanBeReadTest 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,
        ]);

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

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

    private function campaign(array $attributes = []): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Winter Sale',
            'platform' => 'meta',
            'status' => 'published',
            'objective' => 'OUTCOME_TRAFFIC',
            'ad_account_id' => 'act_111',
            'currency' => 'USD',
            'budget' => 25,
            'budget_mode' => 'daily',
            'external_campaign_id' => '120252047635070626',
            ...$attributes,
        ]);

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

        return $campaign;
    }

    private function read(array $arguments = []): array
    {
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($candidate): bool => $candidate->name() === 'campaign__read_delivery');

        $this->assertNotNull($tool, 'campaign__read_delivery is not registered');
        /** @var NamespacedTool $tool */

        return json_decode((string) $tool->handle(new ToolRequest($arguments)), true);
    }

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

        Http::fake(function (Request $request) {
            $path = parse_url($request->url(), PHP_URL_PATH) ?? '';
            $query = [];
            parse_str((string) parse_url($request->url(), PHP_URL_QUERY), $query);

            if (str_ends_with($path, '/campaigns')) {
                $this->assertStringContainsString('PAUSED', (string) ($query['filtering'] ?? ''));
                $this->assertStringContainsString('ACTIVE', (string) ($query['filtering'] ?? ''));

                return Http::response(['data' => [
                    [
                        'id' => '111',
                        'name' => 'Live',
                        'status' => 'ACTIVE',
                        'effective_status' => 'ACTIVE',
                        'daily_budget' => '2500',
                        'bid_strategy' => 'LOWEST_COST_WITHOUT_CAP',
                    ],
                    [
                        'id' => '222',
                        'name' => 'Resting',
                        'status' => 'PAUSED',
                        'effective_status' => 'PAUSED',
                        'lifetime_budget' => '10000',
                        'bid_strategy' => 'COST_CAP',
                    ],
                    [
                        'id' => '333',
                        'name' => 'Old',
                        'status' => 'ARCHIVED',
                        'effective_status' => 'ARCHIVED',
                        'daily_budget' => '100',
                    ],
                    [
                        'id' => '444',
                        'name' => 'Quiet',
                        'status' => 'ACTIVE',
                        'effective_status' => 'ACTIVE',
                        'daily_budget' => '1000',
                    ],
                ]]);
            }

            if (str_ends_with($path, '/insights')) {
                return Http::response(['data' => [
                    ['campaign_id' => '111', 'spend' => '12.50'],
                    ['campaign_id' => '222', 'spend' => '40.00'],
                ]]);
            }

            if (str_ends_with($path, '/act_111')) {
                return Http::response(['id' => 'act_111', 'currency' => 'USD']);
            }

            return Http::response(['error' => ['message' => 'unexpected '.$path]], 500);
        });

        $result = $this->read(['all_campaigns' => true]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('USD', $result['currency']);
        $this->assertSame('lifetime', $result['spend_period']);
        $this->assertSame(['111', '222', '444'], array_column($result['campaigns'], 'id'));
        $this->assertSame(25, $result['campaigns'][0]['daily_budget']);
        $this->assertNull($result['campaigns'][0]['lifetime_budget']);
        $this->assertSame(12.5, $result['campaigns'][0]['spend']);
        $this->assertSame('campaign', $result['campaigns'][0]['budget_level']);
        $this->assertSame('PAUSED', $result['campaigns'][1]['effective_status']);
        $this->assertSame(100, $result['campaigns'][1]['lifetime_budget']);
        $this->assertSame(40, $result['campaigns'][1]['spend']);
        $this->assertSame('campaign', $result['campaigns'][1]['budget_level']);
        $this->assertNull($result['campaigns'][2]['spend']);
        $this->assertArrayNotHasKey('ad_sets', $result['campaigns'][0]);
    }

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

        Http::fake(function (Request $request) {
            $path = parse_url($request->url(), PHP_URL_PATH) ?? '';
            $query = [];
            parse_str((string) parse_url($request->url(), PHP_URL_QUERY), $query);

            if (str_ends_with($path, '/adsets')) {
                $this->assertStringContainsString('PAUSED', (string) ($query['filtering'] ?? ''));

                return Http::response(['data' => [
                    [
                        'id' => 'adset-live',
                        'name' => 'US',
                        'status' => 'ACTIVE',
                        'effective_status' => 'CAMPAIGN_PAUSED',
                        'daily_budget' => '1500',
                        'bid_strategy' => 'COST_CAP',
                        'bid_amount' => '250',
                        'daily_spend_cap' => '5000',
                        'pacing_type' => ['standard'],
                        'start_time' => '2026-01-01T00:00:00+0000',
                        'end_time' => '2026-02-01T00:00:00+0000',
                        'adset_schedule' => [['days' => [1, 2], 'start_minute' => 480, 'end_minute' => 1020]],
                        'optimization_goal' => 'OFFSITE_CONVERSIONS',
                        'destination_type' => 'WEBSITE',
                        'billing_event' => 'IMPRESSIONS',
                        'attribution_spec' => [['event_type' => 'CLICK_THROUGH', 'window_days' => 7]],
                        'is_dynamic_creative' => false,
                        'promoted_object' => ['pixel_id' => '555', 'custom_event_type' => 'PURCHASE'],
                        'targeting' => [
                            'geo_locations' => ['countries' => ['US']],
                            'age_min' => 25,
                            'age_max' => 54,
                            'genders' => [1],
                            'publisher_platforms' => ['facebook', 'instagram'],
                            'facebook_positions' => ['feed'],
                            'instagram_positions' => ['stream'],
                            'device_platforms' => ['mobile'],
                            'user_os' => ['iOS'],
                            'wireless_carrier' => ['Wifi'],
                            'targeting_automation' => ['advantage_audience' => 0],
                        ],
                    ],
                    [
                        'id' => 'adset-paused',
                        'name' => 'UK',
                        'status' => 'PAUSED',
                        'effective_status' => 'PAUSED',
                        'lifetime_budget' => '8000',
                        'bid_strategy' => 'LOWEST_COST_WITH_MIN_ROAS',
                        'bid_constraints' => ['roas_average_floor' => 25000],
                    ],
                    [
                        'id' => 'adset-old',
                        'name' => 'Archived',
                        'status' => 'ARCHIVED',
                        'effective_status' => 'ARCHIVED',
                        'daily_budget' => '100',
                    ],
                ]]);
            }

            if (str_ends_with($path, '/insights')) {
                if (($query['level'] ?? '') === 'adset') {
                    return Http::response(['data' => [
                        ['adset_id' => 'adset-live', 'spend' => '8.25'],
                    ]]);
                }

                return Http::response(['data' => [['spend' => '48.25', 'impressions' => '1000']]]);
            }

            if (str_ends_with($path, '/act_111')) {
                return Http::response(['id' => 'act_111', 'currency' => 'USD']);
            }

            if (str_ends_with($path, '/120252047635070626')) {
                return Http::response([
                    'id' => '120252047635070626',
                    'name' => 'Winter Sale',
                    'status' => 'PAUSED',
                    'effective_status' => 'PAUSED',
                    'account_id' => '111',
                    'daily_budget' => '5000',
                    'bid_strategy' => 'LOWEST_COST_WITHOUT_CAP',
                    'start_time' => '2026-01-01T00:00:00+0000',
                    'stop_time' => '2026-03-01T00:00:00+0000',
                ]);
            }

            return Http::response(['error' => ['message' => 'unexpected '.$path]], 500);
        });

        $result = $this->read(['campaign_id' => '120252047635070626']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $campaign = $result['campaigns'][0];
        $this->assertSame('PAUSED', $campaign['effective_status']);
        $this->assertSame(50, $campaign['daily_budget']);
        $this->assertSame(48.25, $campaign['spend']);
        $this->assertSame(['adset-live', 'adset-paused'], array_column($campaign['ad_sets'], 'id'));
        $this->assertSame(15, $campaign['ad_sets'][0]['daily_budget']);
        $this->assertSame(2.5, $campaign['ad_sets'][0]['bid_amount']);
        $this->assertSame(50, $campaign['ad_sets'][0]['daily_spend_cap']);
        $this->assertSame(8.25, $campaign['ad_sets'][0]['spend']);
        $this->assertSame('CAMPAIGN_PAUSED', $campaign['ad_sets'][0]['effective_status']);
        $this->assertSame(80, $campaign['ad_sets'][1]['lifetime_budget']);
        $this->assertSame(2.5, $campaign['ad_sets'][1]['roas_average_floor']);
        $this->assertNull($campaign['ad_sets'][1]['spend']);
        $this->assertSame('lifetime', $result['spend_period']);
        $this->assertSame('2026-01-01T00:00:00+0000', $campaign['start_time']);
        $this->assertSame('2026-03-01T00:00:00+0000', $campaign['end_time']);
        $adSet = $campaign['ad_sets'][0];
        $this->assertSame(['standard'], $adSet['pacing_type']);
        $this->assertSame('2026-02-01T00:00:00+0000', $adSet['end_time']);
        $this->assertSame([['days' => [1, 2], 'start_minute' => 480, 'end_minute' => 1020]], $adSet['adset_schedule']);
        $this->assertSame(['countries' => ['US']], $adSet['targeting']['geo_locations']);
        $this->assertSame(25, $adSet['targeting']['age_min']);
        $this->assertSame(0, $adSet['targeting']['advantage_audience']);
        $this->assertSame(['facebook', 'instagram'], $adSet['placements']['publisher_platforms']);
        $this->assertSame(['feed'], $adSet['placements']['facebook_positions']);
        $this->assertSame(['mobile'], $adSet['devices']['device_platforms']);
        $this->assertSame(['Wifi'], $adSet['devices']['wireless_carrier']);
        $this->assertSame('OFFSITE_CONVERSIONS', $adSet['optimization_goal']);
        $this->assertSame('PURCHASE', $adSet['conversion_event']);
        $this->assertSame('WEBSITE', $adSet['destination_type']);
        $this->assertSame('IMPRESSIONS', $adSet['billing_event']);
        $this->assertFalse($adSet['is_dynamic_creative']);
        $this->assertContains('attribution_spec', $adSet['locked_fields']);
    }

    public function test_a_yen_budget_is_not_divided_by_one_hundred(): void
    {
        $this->campaign(['currency' => 'JPY']);

        Http::fake(function (Request $request) {
            $path = parse_url($request->url(), PHP_URL_PATH) ?? '';
            $query = [];
            parse_str((string) parse_url($request->url(), PHP_URL_QUERY), $query);

            if (str_ends_with($path, '/adsets')) {
                return Http::response(['data' => [[
                    'id' => 'adset-1',
                    'name' => 'Japan',
                    'status' => 'ACTIVE',
                    'effective_status' => 'ACTIVE',
                    'daily_budget' => '3000',
                    'bid_amount' => '120',
                ]]]);
            }

            if (str_ends_with($path, '/insights')) {
                return Http::response(['data' => ($query['level'] ?? '') === 'adset'
                    ? [['adset_id' => 'adset-1', 'spend' => '500']]
                    : [['spend' => '500', 'impressions' => '10']]]);
            }

            if (str_ends_with($path, '/act_111')) {
                return Http::response(['id' => 'act_111', 'currency' => 'JPY']);
            }

            if (str_ends_with($path, '/120252047635070626')) {
                return Http::response([
                    'id' => '120252047635070626',
                    'name' => 'Winter Sale',
                    'status' => 'ACTIVE',
                    'effective_status' => 'ACTIVE',
                    'account_id' => 'act_111',
                ]);
            }

            return Http::response(['error' => ['message' => 'unexpected '.$path]], 500);
        });

        $result = $this->read(['campaign_id' => '120252047635070626']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('JPY', $result['currency']);
        $this->assertSame(3000, $result['campaigns'][0]['ad_sets'][0]['daily_budget']);
        $this->assertSame(120, $result['campaigns'][0]['ad_sets'][0]['bid_amount']);
    }

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

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

            if (str_ends_with($path, '/act_111')) {
                return Http::response(['id' => 'act_111', 'currency' => 'USD']);
            }

            return Http::response([
                'id' => '999',
                'name' => 'Elsewhere',
                'status' => 'ACTIVE',
                'effective_status' => 'ACTIVE',
                'account_id' => 'act_999',
            ]);
        });

        $result = $this->read(['campaign_id' => '999']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('not on act_111', $result['error']);
    }

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

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

            if (str_ends_with($path, '/act_111')) {
                return Http::response(['id' => 'act_111', 'currency' => 'USD']);
            }

            return Http::response([
                'id' => '120252047635070626',
                'name' => 'Old',
                'status' => 'ARCHIVED',
                'effective_status' => 'ARCHIVED',
                'account_id' => '111',
            ]);
        });

        $result = $this->read(['campaign_id' => '120252047635070626']);

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

    public function test_a_missing_campaign_asks_for_an_id_or_name(): void
    {
        $this->campaign();
        Http::fake();

        $result = $this->read();

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('campaign id or name', $result['error']);
        $this->assertStringContainsString('list_campaigns', $result['note']);
        Http::assertNothingSent();
    }

    public function test_spend_bid_and_budget_come_from_the_warehouse_when_it_has_them(): void
    {
        $this->campaign();
        $this->warehouseDelivery(spend: 12.5);

        Http::fake();

        $result = $this->read(['campaign_id' => '120252047635070626']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('whale', $result['source']);
        $this->assertSame('USD', $result['currency']);
        $this->assertSame(25, $result['campaigns'][0]['daily_budget']);
        $this->assertSame('LOWEST_COST_WITH_BID_CAP', $result['campaigns'][0]['bid_strategy']);
        $this->assertSame(3, $result['campaigns'][0]['bid_amount']);
        $this->assertSame(12.5, $result['campaigns'][0]['spend']);
        $this->assertSame('adset-1', $result['campaigns'][0]['ad_sets'][0]['id']);
        $this->assertSame(10, $result['campaigns'][0]['ad_sets'][0]['daily_budget']);
        $this->assertNull($result['campaigns'][0]['ad_sets'][0]['spend']);
        Http::assertNothingSent();
    }

    public function test_a_warehouse_campaign_without_spend_is_read_from_meta(): void
    {
        $this->campaign();
        $this->warehouseDelivery(spend: null);

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

            if (str_ends_with($path, '/act_111')) {
                return Http::response(['id' => 'act_111', 'currency' => 'USD']);
            }

            if (str_ends_with($path, '/adsets')) {
                return Http::response(['data' => [[
                    'id' => 'adset-1',
                    'name' => 'US',
                    'status' => 'ACTIVE',
                    'effective_status' => 'ACTIVE',
                    'daily_budget' => '1000',
                    'bid_strategy' => 'COST_CAP',
                    'bid_amount' => '200',
                ]]]);
            }

            if (str_ends_with($path, '/insights')) {
                return Http::response(['data' => [['spend' => '9.00']]]);
            }

            if (str_ends_with($path, '/120252047635070626')) {
                return Http::response([
                    'id' => '120252047635070626',
                    'name' => 'Winter Sale',
                    'status' => 'PAUSED',
                    'effective_status' => 'PAUSED',
                    'account_id' => '111',
                    'daily_budget' => '4000',
                    'bid_strategy' => 'COST_CAP',
                ]);
            }

            return Http::response(['error' => ['message' => 'unexpected '.$path]], 500);
        });

        $result = $this->read(['campaign_id' => '120252047635070626']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertArrayNotHasKey('source', $result);
        $this->assertSame(40, $result['campaigns'][0]['daily_budget']);
        $this->assertSame(9, $result['campaigns'][0]['spend']);
    }

    private function warehouseDelivery(?float $spend): void
    {
        $schema = Schema::connection('whale');
        $schema->dropIfExists('arb_adops_campaigns');
        $schema->dropIfExists('arb_adops_adsets');
        $stats = 'arb_adops_stats_daily_'.now()->format('Ym');
        $schema->dropIfExists($stats);

        $schema->create('arb_adops_campaigns', function (Blueprint $table): void {
            $table->string('platform');
            $table->string('account_id');
            $table->string('campaign_id');
            $table->string('name');
            $table->string('status')->nullable();
            $table->string('effective_status')->nullable();
            $table->string('currency')->nullable();
            $table->decimal('daily_budget', 12, 2)->nullable();
            $table->decimal('bid_amount', 12, 2)->nullable();
            $table->string('bid_strategy')->nullable();
        });
        $schema->create('arb_adops_adsets', function (Blueprint $table): void {
            $table->string('platform');
            $table->string('campaign_id');
            $table->string('adset_id');
            $table->string('name');
            $table->string('status')->nullable();
            $table->string('effective_status')->nullable();
            $table->decimal('daily_budget', 12, 2)->nullable();
            $table->string('bid_strategy')->nullable();
            $table->decimal('bid_amount', 12, 2)->nullable();
        });
        $schema->create($stats, function (Blueprint $table): void {
            $table->string('platform');
            $table->string('campaign_id');
            $table->date('stat_date');
            $table->decimal('spend', 12, 2)->default(0);
        });

        DB::connection('whale')->table('arb_adops_campaigns')->insert([
            'platform' => 'meta',
            'account_id' => 'act_111',
            'campaign_id' => '120252047635070626',
            'name' => 'Winter Sale',
            'status' => 'PAUSED',
            'effective_status' => 'PAUSED',
            'currency' => 'USD',
            'daily_budget' => 25,
            'bid_amount' => 3,
            'bid_strategy' => 'LOWEST_COST_WITH_BID_CAP',
        ]);
        DB::connection('whale')->table('arb_adops_adsets')->insert([
            'platform' => 'meta',
            'campaign_id' => '120252047635070626',
            'adset_id' => 'adset-1',
            'name' => 'US',
            'status' => 'ACTIVE',
            'effective_status' => 'CAMPAIGN_PAUSED',
            'daily_budget' => 10,
            'bid_strategy' => 'LOWEST_COST_WITH_BID_CAP',
            'bid_amount' => 3,
        ]);

        if ($spend !== null) {
            DB::connection('whale')->table($stats)->insert([
                'platform' => 'meta',
                'campaign_id' => '120252047635070626',
                'stat_date' => now()->toDateString(),
                'spend' => $spend,
            ]);
        }
    }

    public function test_an_account_is_required_when_nothing_is_in_focus(): void
    {
        $result = $this->read();

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