<?php

namespace Tests\Feature;

use App\Http\Middleware\EnsurePlatformSession;
use App\Models\Branch;
use App\Models\Member;
use App\Models\Organization;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class CareReportTest extends TestCase
{
    use RefreshDatabase;

    protected User $user;

    protected Organization $organization;

    protected function setUp(): void
    {
        parent::setUp();
        $this->withoutMiddleware(EnsurePlatformSession::class);

        $this->user = User::create([
            'public_id' => 'test-user-001',
            'name' => 'Test User',
            'email' => 'test@example.com',
        ]);

        $this->organization = Organization::create([
            'owner_ref' => $this->user->public_id,
            'name' => 'Test Clinic',
            'slug' => 'test-clinic',
            'timezone' => 'UTC',
            'settings' => ['onboarded' => true, 'plan' => 'pro', 'plan_expires_at' => now()->addMonth()->toIso8601String()],
        ]);

        Member::create([
            'owner_ref' => $this->user->public_id,
            'organization_id' => $this->organization->id,
            'user_ref' => $this->user->public_id,
            'role' => 'accountant',
        ]);

        Branch::create([
            'owner_ref' => $this->user->public_id,
            'organization_id' => $this->organization->id,
            'name' => 'Main Branch',
            'is_active' => true,
        ]);
    }

    public function test_accountant_can_view_reports(): void
    {
        $this->actingAs($this->user)
            ->get(route('care.reports.index'))
            ->assertOk()
            ->assertSee('Reports');

        $this->actingAs($this->user)
            ->get(route('care.reports.show', 'finance'))
            ->assertOk()
            ->assertSee('Finance');
    }

    public function test_accountant_can_export_report_csv(): void
    {
        $response = $this->actingAs($this->user)
            ->get(route('care.reports.export', [
                'type' => 'finance',
                'from' => now()->subDays(7)->toDateString(),
                'to' => now()->toDateString(),
            ]));

        $response->assertOk();
        $response->assertHeader('content-type', 'text/csv; charset=UTF-8');
        $this->assertStringContainsString('Metric', $response->streamedContent());
    }
}
