<?php

namespace Tests\Feature;

use App\Services\Meta\GraphApi;
use App\Services\Meta\MetaException;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

/**
 * A creative whose file is gone fails in words the buyer can act on.
 *
 * Seen on dev on 23 Sep, at the last step of a real Meta run: the asset rows had
 * been synced from another environment without their files, so uploading the
 * attached creative hit filesize() on a path that did not exist. PHP raised a
 * warning, Laravel turned it into an ErrorException, and the chat printed it
 * whole:
 *
 *   That step failed: filesize(): stat failed for
 *   /var/www/php85/shyam/arb.admedia.com/storage/app/public/creatives/images/SOlj....jpg
 *
 * Two things wrong with that. The buyer cannot do anything with it, and it
 * hands them the absolute server path. ChatController::readableFailure() passes
 * anything it does not recognise straight through, so the guard has to be at
 * the source rather than in the wording of the reply.
 */
class MissingCreativeFileTest extends TestCase
{
    public function test_a_missing_image_file_is_reported_without_the_server_path(): void
    {
        Http::preventStrayRequests();

        $api = app(GraphApi::class);
        $path = storage_path('app/public/creatives/images/does-not-exist.jpg');

        try {
            $api->uploadImage('act_1238155271384134', $path, 'summer-sale.jpg');
            $this->fail('Uploading a file that does not exist should not be attempted.');
        } catch (MetaException $e) {
            $this->assertStringContainsString(
                'summer-sale.jpg',
                $e->getMessage(),
                'The buyer should be told which creative is missing.',
            );

            $this->assertStringNotContainsString(
                storage_path(),
                $e->getMessage(),
                'The absolute server path must not reach the buyer.',
            );

            $this->assertStringNotContainsString(
                'stat failed',
                $e->getMessage(),
                'A raw PHP warning is not an explanation.',
            );
        }
    }

    /**
     * Videos take the same path, and the same guard has to cover them.
     *
     * uploadVideo() calls the same multipart() helper, so this would be a
     * duplicate were the guard ever moved up into the two callers.
     */
    public function test_a_missing_video_file_is_reported_the_same_way(): void
    {
        Http::preventStrayRequests();

        $this->expectException(MetaException::class);
        $this->expectExceptionMessage('The file for launch.mp4 is missing');

        app(GraphApi::class)->uploadVideo(
            'act_1238155271384134',
            storage_path('app/public/creatives/videos/does-not-exist.mp4'),
            'launch.mp4',
        );
    }
}
