<?php

namespace Tests\Tenant\Controllers;

use App\Models\ExternalApiToken;
use App\Modules\VehiclesInVideo\Services\TokenService;
use Tests\TenantTestCase;

class VehiclesInVideoNotificationControllerTest extends TenantTestCase
{
    public function testWebhookStoresTokens(): void
    {
        $payload = [
            'auth_token' => 'auth-abc',
            'refresh_token' => 'refresh-xyz',
            'auth_token_expiry_secs' => 3600,
            'refresh_token_expiry_secs' => 86400,
        ];

        $response = $this->postJson(
            route('tenant.notifications.vehicles-in-video.store', tenant('id')),
            $payload
        );

        $response->assertStatus(200);

        $token = ExternalApiToken::where('provider', TokenService::PROVIDER)->latest()->first();
        $this->assertNotNull($token);
        $this->assertEquals('auth-abc', $token->auth_token);
        $this->assertEquals('refresh-xyz', $token->refresh_token);
        $this->assertTrue($token->isConnected());
        $this->assertTrue($token->auth_expires_at->isFuture());
        $this->assertTrue($token->refresh_expires_at->isFuture());
    }

    public function testWebhookMissingTokensReturns400(): void
    {
        $response = $this->postJson(
            route('tenant.notifications.vehicles-in-video.store', tenant('id')),
            ['auth_token' => 'auth-only']
        );

        $response->assertStatus(400);
        $this->assertEquals(0, ExternalApiToken::count());
    }

    public function testWebhookUpdatesExistingProviderToken(): void
    {
        $existing = ExternalApiToken::create([
            'provider' => TokenService::PROVIDER,
            'auth_token' => 'old-auth',
            'refresh_token' => 'old-refresh',
        ]);
        $otherProvider = ExternalApiToken::create([
            'provider' => 'some-other-provider',
            'auth_token' => 'keep-auth',
            'refresh_token' => 'keep-refresh',
        ]);

        $this->postJson(
            route('tenant.notifications.vehicles-in-video.store', tenant('id')),
            [
                'auth_token' => 'new-auth',
                'refresh_token' => 'new-refresh',
            ]
        )->assertStatus(200);

        $token = ExternalApiToken::where('provider', TokenService::PROVIDER)->latest()->first();
        $this->assertEquals($existing->id, $token->id);
        $this->assertEquals('new-auth', $token->auth_token);
        $this->assertEquals('new-refresh', $token->refresh_token);
        $this->assertNotNull($otherProvider->fresh());
    }
}
