<?php

namespace Tests\Feature\Api\Event;

use App\Models\Event;
use App\Models\PushSubscription;
use App\Models\Tenant;
use App\Services\EventJoinTokenService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class PushSubscriptionApiTest extends TestCase
{
    use RefreshDatabase;

    public function test_guest_can_register_push_subscription(): void
    {
        $tenant = Tenant::factory()->create();
        $event = Event::factory()->for($tenant)->create(['status' => 'published']);
        $token = app(EventJoinTokenService::class)->createToken($event)->plain_token;

        $payload = [
            'endpoint' => 'https://updates.example.com/push/abc',
            'keys' => [
                'p256dh' => base64_encode('key'),
                'auth' => base64_encode('auth'),
            ],
        ];

        $response = $this->withHeaders(['X-Device-Id' => 'device-test-1'])
            ->postJson("/api/v1/events/{$token}/push-subscriptions", $payload);

        $response->assertCreated();
        $this->assertDatabaseHas('push_subscriptions', [
            'event_id' => $event->id,
            'device_id' => 'device-test-1',
            'endpoint' => $payload['endpoint'],
            'status' => 'active',
        ]);
    }

    public function test_guest_can_revoke_push_subscription(): void
    {
        $tenant = Tenant::factory()->create();
        $event = Event::factory()->for($tenant)->create(['status' => 'published']);
        $token = app(EventJoinTokenService::class)->createToken($event)->plain_token;

        $subscription = PushSubscription::factory()
            ->for($tenant)
            ->for($event)
            ->create([
                'endpoint' => 'https://updates.example.com/push/cached',
                'device_id' => 'device-revoke',
            ]);

        $response = $this->deleteJson("/api/v1/events/{$token}/push-subscriptions", [
            'endpoint' => $subscription->endpoint,
        ]);

        $response->assertOk()->assertJsonPath('status', 'revoked');
        $this->assertDatabaseHas('push_subscriptions', [
            'id' => $subscription->id,
            'status' => 'revoked',
        ]);
    }
}
