<?php

namespace Tests\Feature;

use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Mcp\Tools\GoogleAds\CreateVideoAsset;
use App\Mcp\Tools\GoogleAds\SelectGoogleImageAsset;
use App\Models\Asset;
use App\Models\Campaign;
use App\Models\Creative;
use App\Models\GoogleAdsConnection;
use App\Models\User;
use App\Services\GoogleAdsService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Storage;
use Laravel\Mcp\Request;
use Mockery;
use Tests\TestCase;

class GoogleChatGoogleMediaAssetToolsTest extends TestCase
{
    use RefreshDatabase;

    private User $user;

    private Campaign $campaign;

    protected function setUp(): void
    {
        parent::setUp();
        Storage::fake('local');
        config([
            'platforms.guardrails.allowed_ad_accounts' => ['google:*'],
            'services.google_ads.refresh_token' => 'refresh-token',
            'services.google_ads.customer_id' => '1111111111',
        ]);

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

        $workspace = app(Workspace::class);
        $workspace->bindTo('google-media-assets');
        $workspace->ownedBy($this->user);
        $this->campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Display',
            'platform' => 'google',
            'status' => 'published',
            'ad_account_id' => '2222222222',
            'external_campaign_id' => '101',
        ]);
        $workspace->produced($this->campaign);
        $workspace->focusOn($this->campaign);
    }

    public function test_image_and_video_asset_tools_are_registered_in_campaign_chat(): void
    {
        $names = collect(app(ToolRegistry::class)->resolve(['campaign']))
            ->map(fn ($tool): string => $tool->name());

        $this->assertContains('campaign__select_google_image_asset', $names);
        $this->assertContains('campaign__create_video_asset', $names);
    }

    public function test_google_chat_can_upload_display_logos_for_the_focused_campaign(): void
    {
        $logo = $this->imageCreative(512, 128, '4:1', 'brand-logo.png');
        $squareLogo = $this->imageCreative(128, 128, '1:1', 'square-logo.png');
        $logoBytes = Storage::disk('local')->get($logo->asset->path);
        $squareLogoBytes = Storage::disk('local')->get($squareLogo->asset->path);

        $googleAds = Mockery::mock(GoogleAdsService::class);
        $googleAds->shouldReceive('createImageAsset')
            ->once()
            ->with(
                Mockery::on(fn (GoogleAdsConnection $connection): bool => $connection->customer_id === '2222222222'),
                $logoBytes,
                'brand-logo.png',
            )
            ->andReturn('customers/2222222222/assets/1');
        $googleAds->shouldReceive('createImageAsset')
            ->once()
            ->with(
                Mockery::on(fn (GoogleAdsConnection $connection): bool => $connection->customer_id === '2222222222'),
                $squareLogoBytes,
                'square-logo.png',
            )
            ->andReturn('customers/2222222222/assets/2');
        $this->app->instance(GoogleAdsService::class, $googleAds);

        $logoResult = $this->selectImage($logo->id, 'logo_images');
        $squareLogoResult = $this->selectImage($squareLogo->id, 'square_logo_images');

        $this->assertSame('customers/2222222222/assets/1', $logoResult['asset_resource_name']);
        $this->assertSame('logo_images', $logoResult['image_field']);
        $this->assertSame('customers/2222222222/assets/2', $squareLogoResult['asset_resource_name']);
        $this->assertSame('square_logo_images', $squareLogoResult['image_field']);
    }

    public function test_image_picker_rejects_wrong_logo_dimensions_and_account_ids(): void
    {
        $squareImage = $this->imageCreative(512, 512, '1:1', 'square.png');
        $googleAds = Mockery::mock(GoogleAdsService::class);
        $googleAds->shouldNotReceive('createImageAsset');
        $this->app->instance(GoogleAdsService::class, $googleAds);

        $wrongDimensions = app(SelectGoogleImageAsset::class)->handle(new Request([
            'creative_id' => $squareImage->id,
            'image_field' => 'logo_images',
        ]));
        $wrongAccount = app(SelectGoogleImageAsset::class)->handle(new Request([
            'creative_id' => $squareImage->id,
            'image_field' => 'square_logo_images',
            'customer_id' => '3333333333',
        ]));

        $this->assertTrue($wrongDimensions->isError());
        $this->assertTrue($wrongAccount->isError());
        $this->assertStringContainsString('does not match', (string) $wrongAccount->content());
    }

    public function test_video_asset_creation_uses_the_focused_google_campaign_account(): void
    {
        $googleAds = Mockery::mock(GoogleAdsService::class);
        $googleAds->shouldReceive('createYouTubeVideoAsset')
            ->once()
            ->with(
                Mockery::on(fn (GoogleAdsConnection $connection): bool => $connection->customer_id === '2222222222'),
                'abcDEF12345',
                'Display video',
            )
            ->andReturn('customers/2222222222/assets/3');
        $this->app->instance(GoogleAdsService::class, $googleAds);

        $response = app(CreateVideoAsset::class)->handle(new Request([
            'video_id' => 'abcDEF12345',
            'name' => 'Display video',
        ]));
        $result = json_decode((string) $response->content(), true, flags: JSON_THROW_ON_ERROR);

        $this->assertSame('customers/2222222222/assets/3', $result['asset_resource_name']);
        $this->assertStringContainsString('responsive Display ad', $result['next_step']);
    }

    private function imageCreative(int $width, int $height, string $ratio, string $name): Creative
    {
        $image = imagecreatetruecolor($width, $height);
        ob_start();
        imagepng($image);
        $contents = ob_get_clean();
        imagedestroy($image);
        if ($contents === false) {
            $this->fail('Could not generate test image bytes.');
        }

        $asset = Asset::create([
            'owner_type' => $this->user->getMorphClass(),
            'owner_id' => $this->user->getKey(),
            'kind' => 'image',
            'source' => 'upload',
            'disk' => 'local',
            'path' => 'creatives/'.$name,
            'original_name' => $name,
            'mime' => 'image/png',
            'bytes' => strlen($contents),
            'checksum' => hash('sha256', $contents),
        ]);
        Storage::disk('local')->put($asset->path, $contents);

        return Creative::create([
            'user_id' => $this->user->getKey(),
            'type' => 'image',
            'status' => 'completed',
            'source' => 'upload',
            'ratio' => $ratio,
            'title' => $name,
            'asset_id' => $asset->id,
        ]);
    }

    /** @return array<string, mixed> */
    private function selectImage(int $creativeId, string $field): array
    {
        $response = app(SelectGoogleImageAsset::class)->handle(new Request([
            'creative_id' => $creativeId,
            'image_field' => $field,
        ]));

        return json_decode((string) $response->content(), true, flags: JSON_THROW_ON_ERROR);
    }
}
