<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\File;
use Tests\TestCase;

class HealthcheckTest extends TestCase
{
    use RefreshDatabase;

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

        $linkPath = public_path('storage');
        $targetPath = storage_path('app/public');

        if (is_link($linkPath) || is_file($linkPath)) {
            unlink($linkPath);
        }

        if (is_dir($linkPath) && !is_link($linkPath)) {
            File::deleteDirectory($linkPath);
        }

        if (!is_dir($targetPath)) {
            File::makeDirectory($targetPath, 0755, true);
        }

        symlink($targetPath, $linkPath);
    }

    public function test_healthcheck_endpoint_returns_empty_body_by_default(): void
    {
        $response = $this->get('/healthcheck');

        $response
            ->assertOk()
            ->assertHeader('Content-Type', 'text/plain; charset=UTF-8')
            ->assertContent('');
    }

    public function test_healthcheck_endpoint_returns_diagnostics_with_valid_secret(): void
    {
        config(['services.healthcheck.secret' => 'health-secret']);

        $response = $this->get('/healthcheck?secret=health-secret');

        $response
            ->assertOk()
            ->assertHeader('Content-Type', 'text/plain; charset=UTF-8')
            ->assertSeeText('db: OK')
            ->assertSeeText('cache: OK')
            ->assertSeeText('storage: OK')
            ->assertSeeText('storage_link: OK');
    }

    /**
     * El modo diagnóstico no debe filtrar checks cuando el secreto no coincide,
     * aunque la persona conozca el flag `printresumen=true`.
     */
    public function test_healthcheck_endpoint_hides_diagnostics_with_invalid_secret(): void
    {
        config(['services.healthcheck.secret' => 'health-secret']);

        $response = $this->get('/healthcheck?secret=otro-secreto');

        $response
            ->assertOk()
            ->assertHeader('Content-Type', 'text/plain; charset=UTF-8')
            ->assertContent('');
    }
}
