<?php

namespace Tests\Feature\Api;

use App\Models\Tenant;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\File;
use Tests\TestCase;

class TenantFontsTest extends TestCase
{
    use RefreshDatabase;

    private ?string $manifestBackup = null;

    protected function setUp(): void
    {
        parent::setUp();

        $manifestPath = public_path('fonts/google/manifest.json');
        if (File::exists($manifestPath)) {
            $this->manifestBackup = File::get($manifestPath);
        }
    }

    protected function tearDown(): void
    {
        $manifestPath = public_path('fonts/google/manifest.json');
        if ($this->manifestBackup !== null) {
            File::put($manifestPath, $this->manifestBackup);
        } else {
            File::delete($manifestPath);
        }

        parent::tearDown();
    }

    public function test_tenant_can_fetch_font_manifest(): void
    {
        $manifestPath = public_path('fonts/google/manifest.json');
        File::ensureDirectoryExists(dirname($manifestPath));

        File::put($manifestPath, json_encode([
            'fonts' => [
                [
                    'family' => 'Manifest Font',
                    'category' => 'sans-serif',
                    'variants' => [
                        ['variant' => 'regular', 'weight' => 400, 'style' => 'normal', 'url' => '/fonts/google/manifest-font/regular.woff2'],
                    ],
                ],
            ],
        ]));

        $tenant = Tenant::factory()->create();
        $user = User::factory()->create([
            'tenant_id' => $tenant->id,
            'role' => 'tenant_admin',
        ]);

        $token = $user->createToken('test')->plainTextToken;

        $response = $this->withHeader('Authorization', 'Bearer '.$token)
            ->getJson('/api/v1/tenant/fonts');

        $response->assertOk();
        $response->assertJsonStructure(['data']);
        $this->assertTrue(collect($response->json('data'))->pluck('family')->contains('Manifest Font'));
    }
}
