<?php

namespace Tests\Feature;

use Illuminate\Support\Facades\Storage;
use Tests\TestCase;

class LauncherAppcastTest extends TestCase
{
    public function test_update_appcast_requires_launcher_auth_header(): void
    {
        config(['auth.launcher_auth_key' => 'launcher-secret']);

        $response = $this->call(
            method: 'POST',
            uri: '/api/service/update-appcast',
            content: $this->appcastXml(),
        );

        $response->assertForbidden();
    }

    public function test_update_appcast_saves_raw_xml_to_public_storage(): void
    {
        Storage::fake('public');
        config(['auth.launcher_auth_key' => 'launcher-secret']);

        $xml = $this->appcastXml();

        $response = $this->call(
            method: 'POST',
            uri: '/api/service/update-appcast',
            server: [
                'HTTP_AUTH' => 'launcher-secret',
                'CONTENT_TYPE' => 'application/xml',
            ],
            content: $xml,
        );

        $response
            ->assertOk()
            ->assertJson(['message' => 'XML saved']);

        Storage::disk('public')->assertExists('appcast.xml');
        $this->assertSame($xml, Storage::disk('public')->get('appcast.xml'));
    }

    private function appcastXml(): string
    {
        return <<<'XML'
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle">
  <channel>
    <title>Moonwell Launcher - Appcast</title>
    <item>
      <title>Version 1.2.0</title>
      <description>Launcher update.</description>
      <pubDate>Sat, 16 May 2026 12:00:00 +0400</pubDate>
      <enclosure url="https://moonwell.su/launcher/download" sparkle:version="1.2.0" sparkle:os="windows" />
    </item>
  </channel>
</rss>
XML;
    }
}
