<?php

namespace Tests\Feature;

use App\Models\Contact;
use App\Models\Conversation;
use App\Models\Membership;
use App\Models\Organization;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class DashboardTest extends TestCase
{
    use RefreshDatabase;

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

        $response->assertRedirect('/login');
    }

    public function test_authenticated_user_can_view_dashboard(): void
    {
        $user = User::factory()->create([
            'name' => 'Admin User',
        ]);

        $response = $this->actingAs($user)->get('/dashboard');

        $response->assertOk();
        $response->assertSee('Dashboard');
        $response->assertSee('Admin User');
    }

    public function test_dashboard_displays_open_conversation_count_for_users_organization(): void
    {
        $user = User::factory()->create();
        $organization = Organization::factory()->create();
        $contact = Contact::factory()->create([
            'organization_id' => $organization->id,
        ]);

        Membership::factory()->create([
            'organization_id' => $organization->id,
            'user_id' => $user->id,
        ]);

        Conversation::factory()->count(2)->create([
            'organization_id' => $organization->id,
            'contact_id' => $contact->id,
            'status' => 'open',
        ]);

        Conversation::factory()->create([
            'organization_id' => $organization->id,
            'contact_id' => $contact->id,
            'status' => 'closed',
        ]);

        $response = $this->actingAs($user)->get('/dashboard');

        $response->assertOk();
        $response->assertSee('Open conversations');
        $response->assertSee('2');
    }
}
