<?php

namespace Tests\Feature;

use App\Agent\Workspace;
use App\Http\Controllers\ChatController;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use ReflectionMethod;
use Tests\TestCase;

class AdCopyCanBeReadTest 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-ad-copy');
        app(Workspace::class)->ownedBy($this->user);
    }

    public function test_asking_in_chat_shows_the_copy_stored_on_the_link(): void
    {
        $this->campaign();
        Http::fake([
            '*120248508119250429*' => Http::response([
                'id' => '120248508119250429',
                'name' => 'Browse Without the Clutter',
                'status' => 'ACTIVE',
                'effective_status' => 'CAMPAIGN_PAUSED',
                'campaign_id' => '120248506018230429',
                'creative' => [
                    'id' => 'creative-1',
                    'body' => '',
                    'title' => '',
                    'object_story_spec' => [
                        'link_data' => [
                            'message' => 'Shop the quieter feed.',
                            'name' => 'Less noise',
                            'description' => 'A calmer home page.',
                            'link' => 'https://example.com/quiet',
                        ],
                    ],
                ],
            ]),
        ]);

        $reply = $this->ask('can you share primary text, headline and description of this ad id 120248508119250429 from this campaign 120248506018230429');

        $this->assertStringContainsString('Browse Without the Clutter (120248508119250429). Status ACTIVE. Effective status CAMPAIGN_PAUSED.', $reply);
        $this->assertStringContainsString('Primary text: Shop the quieter feed.', $reply);
        $this->assertStringContainsString('Headline: Less noise', $reply);
        $this->assertStringContainsString('Description: A calmer home page.', $reply);
        $this->assertStringContainsString('URL: https://example.com/quiet', $reply);
        Http::assertSent(function ($request): bool {
            return $request->method() === 'GET'
                && str_contains((string) $request->data()['fields'], 'object_story_spec')
                && str_contains((string) $request->data()['fields'], 'asset_feed_spec')
                && str_ends_with((string) parse_url($request->url(), PHP_URL_PATH), '/120248508119250429');
        });
    }

    public function test_a_dynamic_creative_uses_the_asset_feed_when_body_and_title_are_empty(): void
    {
        $this->campaign();
        Http::fake([
            '*120248508119250429*' => Http::response([
                'name' => 'Dynamic',
                'status' => 'PAUSED',
                'effective_status' => 'PAUSED',
                'campaign_id' => '120248506018230429',
                'creative' => [
                    'body' => '',
                    'title' => '',
                    'asset_feed_spec' => [
                        'bodies' => [['text' => 'First body'], ['text' => 'Second body']],
                        'titles' => [['text' => 'Feed headline']],
                        'descriptions' => [['text' => 'Feed description']],
                    ],
                ],
            ]),
        ]);

        $reply = $this->ask('show the primary text, headline and description of ad 120248508119250429');

        $this->assertStringContainsString("Primary text: First body\nSecond body", $reply);
        $this->assertStringContainsString('Headline: Feed headline', $reply);
        $this->assertStringContainsString('Description: Feed description', $reply);
    }

    public function test_an_ad_from_another_campaign_is_not_shown(): void
    {
        $this->campaign();
        Http::fake([
            '*' => Http::response([
                'name' => 'Other',
                'status' => 'ACTIVE',
                'effective_status' => 'ACTIVE',
                'campaign_id' => '999999999999',
                'creative' => ['body' => 'Secret', 'title' => 'Nope'],
            ]),
        ]);

        $reply = $this->ask('share the headline of ad 120248508119250429 from campaign 120248506018230429');

        $this->assertSame('Ad 120248508119250429 is not in campaign 120248506018230429.', $reply);
        $this->assertStringNotContainsString('Secret', $reply);
    }

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

        $reply = $this->ask('write a headline and primary text for this ad');

        $this->assertNull($reply);
        Http::assertNothingSent();
    }

    private function ask(string $message): ?string
    {
        return (new ReflectionMethod(ChatController::class, 'adCopyFromMessage'))
            ->invoke(app(ChatController::class), $message);
    }

    private function campaign(): 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' => '120248506018230429',
        ]);

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

        return $campaign;
    }
}
