<?php

namespace Tests\Feature;

use App\Models\TableSnapshot;
use App\Models\User;
use App\Models\Website;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;

class HarnessAgentApiTest extends TestCase
{
    use RefreshDatabase;

    public function test_health_endpoint_accepts_valid_signed_requests(): void
    {
        $website = $this->makeHarnessWebsite();
        $timestamp = now()->toIso8601String();

        $response = $this->withHeaders($this->headersFor($website, 'GET', '/health', $timestamp))
            ->getJson(route('harness.health', $website));

        $response
            ->assertOk()
            ->assertJsonPath('status', 'online')
            ->assertJsonPath('health', 'healthy');
    }

    public function test_health_endpoint_rejects_invalid_credentials(): void
    {
        $website = $this->makeHarnessWebsite();
        $timestamp = now()->toIso8601String();
        $headers = $this->headersFor($website, 'GET', '/health', $timestamp);
        $headers['Authorization'] = 'Bearer wrong-token';

        $this->withHeaders($headers)
            ->getJson(route('harness.health', $website))
            ->assertUnauthorized();
    }

    public function test_backup_endpoint_creates_a_downloadable_file(): void
    {
        Storage::fake('local');

        $website = $this->makeHarnessWebsite();
        $timestamp = now()->toIso8601String();

        $response = $this->withHeaders($this->headersFor($website, 'POST', '/backups', $timestamp))
            ->postJson(route('harness.backups.store', $website), [
                'panel_backup_id' => 44,
                'requested_by' => 'admin@example.com',
            ]);

        $response
            ->assertCreated()
            ->assertJsonPath('status', 'completed');

        Storage::disk('local')->assertExists($response->json('file_path'));
    }

    protected function makeHarnessWebsite(): Website
    {
        $user = User::factory()->superAdmin()->create();
        $website = Website::factory()->for($user, 'createdBy')->create([
            'connection_type' => 'local_harness',
            'api_key' => 'cc_local_harness_token',
            'signing_secret' => 'cc_local_harness_secret',
        ]);

        TableSnapshot::factory()->for($website)->create();

        return $website;
    }

    protected function headersFor(Website $website, string $method, string $path, string $timestamp): array
    {
        $signature = hash_hmac('sha256', "{$method}|{$path}|{$timestamp}", $website->signing_secret ?: $website->api_key);

        return [
            'Authorization' => 'Bearer '.$website->api_key,
            'X-Control-Timestamp' => $timestamp,
            'X-Control-Signature' => $signature,
            'Accept' => 'application/json',
        ];
    }
}
