<?php

namespace Tests\Feature\Services;

use App\Services\SiteDownloadService;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

class SiteDownloadServiceTest extends TestCase
{
    public function testDownloadFilePullsFromDirectUrlWithoutTouchingRemote()
    {
        Http::fake([
            'https://cdn.example.com/*' => Http::response('direct-bytes', 200),
            '*' => Http::response('unexpected', 500),
        ]);

        $contents = $this->service()->downloadFile([
            'path' => 'tenant_x/media/logo.png',
            'url' => 'https://cdn.example.com/tenant_x/media/logo.png',
        ]);

        $this->assertEquals('direct-bytes', $contents);
        Http::assertSent(fn ($request) => $request->url() === 'https://cdn.example.com/tenant_x/media/logo.png');
        Http::assertNotSent(fn ($request) => str_contains($request->url(), '/api/site-export/'));
    }

    public function testDownloadFileFallsBackToStreamingWhenDirectUrlFails()
    {
        Http::fake([
            'https://cdn.example.com/*' => Http::response('', 403),
            'https://remote.example.com/api/site-export/*' => Http::response('streamed-bytes', 200),
        ]);

        $contents = $this->service()->downloadFile([
            'path' => 'tenant_x/media/logo.png',
            'url' => 'https://cdn.example.com/tenant_x/media/logo.png',
        ]);

        $this->assertEquals('streamed-bytes', $contents);
        Http::assertSent(fn ($request) => str_contains($request->url(), '/api/site-export/tenant_x/file'));
    }

    public function testDownloadFileStreamsWhenNoUrlProvided()
    {
        Http::fake([
            'https://remote.example.com/api/site-export/*' => Http::response('streamed-bytes', 200),
        ]);

        $contents = $this->service()->downloadFile([
            'path' => 'tenant_x/media/logo.png',
            'url' => null,
        ]);

        $this->assertEquals('streamed-bytes', $contents);
    }

    private function service(): SiteDownloadService
    {
        $service = app(SiteDownloadService::class);
        $service->setConfig('https://remote.example.com', 'token', 'user@example.com', 'tenant_x');

        return $service;
    }
}
