<?php

namespace Tests\Feature;

use App\Agent\Tools\Campaign\ReviewAssets;
use App\Agent\Workspace;
use App\Models\Asset;
use App\Models\Campaign;
use App\Models\User;
use App\Services\Meta\Meta;
use App\Services\Meta\MetaException;
use Illuminate\Filesystem\FilesystemAdapter;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Storage;
use Laravel\Ai\Tools\Request;
use Tests\TestCase;

class ReviewAssetsStorageTest extends TestCase
{
    use RefreshDatabase;

    private function workspaceWithRemoteAsset(): Asset
    {
        $user = User::factory()->create();
        $this->actingAs($user);

        $workspace = app(Workspace::class);
        $workspace->bindTo('remote-creative');
        $workspace->ownedBy($user);

        $asset = Asset::create([
            'owner_type' => $user->getMorphClass(),
            'owner_id' => $user->getKey(),
            'kind' => 'image',
            'source' => 'generated',
            'disk' => 'remote',
            'path' => 'creatives/images/creative-2.png',
            'original_name' => 'creative-2.png',
            'mime' => 'image/png',
            'bytes' => 10,
        ]);
        $workspace->produced($asset, focus: false);
        $workspace->produced(Campaign::create([
            'user_id' => $user->getKey(),
            'name' => 'Offer campaign',
            'platform' => 'meta',
            'ad_account_id' => 'act_1418821929380936',
            'status' => 'draft',
        ]));

        return $asset;
    }

    public function test_upload_reads_the_disk_when_it_has_no_local_file_path(): void
    {
        $asset = $this->workspaceWithRemoteAsset();
        $disk = $this->createMock(FilesystemAdapter::class);
        $disk->method('exists')->willReturn(true);
        $disk->method('path')->willReturn('/no-local-copy/creative-2.png');
        $disk->method('get')->willReturn('image bytes');
        Storage::shouldReceive('disk')->with('remote')->andReturn($disk);

        $temporaryPath = null;
        $meta = $this->createMock(Meta::class);
        $meta->method('on')->willReturnSelf();
        $meta->expects($this->once())->method('uploadImage')
            ->willReturnCallback(function (string $account, string $path, string $name) use (&$temporaryPath): string {
                $this->assertSame('act_1418821929380936', $account);
                $this->assertSame('creative-2.png', $name);
                $this->assertSame('image bytes', file_get_contents($path));
                $temporaryPath = $path;

                return 'uploaded-hash';
            });

        $result = json_decode((string) (new ReviewAssets(app(Workspace::class), $meta))->handle(new Request([])), true);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('uploaded-hash', $asset->refFor('meta', 'act_1418821929380936')->reference());
        $this->assertNotNull($temporaryPath);
        $this->assertFileDoesNotExist($temporaryPath);
    }

    public function test_missing_original_is_reported_before_any_upload(): void
    {
        $asset = $this->workspaceWithRemoteAsset();
        $disk = $this->createMock(FilesystemAdapter::class);
        $disk->method('exists')->willReturn(false);
        Storage::shouldReceive('disk')->with('remote')->andReturn($disk);

        $meta = $this->createMock(Meta::class);
        $meta->method('on')->willReturnSelf();
        $meta->expects($this->never())->method('uploadImage');

        $result = json_decode((string) (new ReviewAssets(app(Workspace::class), $meta))->handle(new Request([])), true);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('original file', $result['error']);
        $this->assertNull($asset->refFor('meta', 'act_1418821929380936'));
    }

    public function test_a_failed_upload_cleans_up_its_temporary_copy(): void
    {
        $asset = $this->workspaceWithRemoteAsset();
        $disk = $this->createMock(FilesystemAdapter::class);
        $disk->method('exists')->willReturn(true);
        $disk->method('path')->willReturn('/no-local-copy/creative-2.png');
        $disk->method('get')->willReturn('image bytes');
        Storage::shouldReceive('disk')->with('remote')->andReturn($disk);

        $temporaryPath = null;
        $meta = $this->createMock(Meta::class);
        $meta->method('on')->willReturnSelf();
        $meta->expects($this->once())->method('uploadImage')
            ->willReturnCallback(function (string $account, string $path) use (&$temporaryPath): never {
                $temporaryPath = $path;

                throw new MetaException('Provider rejected the upload.');
            });

        $result = json_decode((string) (new ReviewAssets(app(Workspace::class), $meta))->handle(new Request([])), true);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('Provider rejected the upload', $result['error']);
        $this->assertNotNull($temporaryPath);
        $this->assertFileDoesNotExist($temporaryPath);
        $this->assertNull($asset->refFor('meta', 'act_1418821929380936'));
    }
}
