<?php

namespace Tests\Browser;

use App\Models\Project;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\Browser;
use Tests\DuskTestCase;

class ProjectWorkflowTest extends DuskTestCase
{
    use DatabaseMigrations;

    public function test_user_can_login_and_create_project()
    {
        $user = User::factory()->create([
            'email' => 'test@example.com',
            'password' => bcrypt('password'),
        ]);

        $this->browse(function (Browser $browser) use ($user) {
            $browser->visit('/login')
                    ->type('email', 'test@example.com')
                    ->type('password', 'password')
                    ->press('LOG IN')
                    ->assertPathIs('/dashboard')
                    ->visit('/projects/create')
                    ->type('name', 'Test Project from Dusk')
                    ->type('address', '123 Test Street')
                    ->press('Guardar')
                    ->assertPathBeginsWith('/projects/')
                    ->assertSee('Test Project from Dusk');
        });
    }

    public function test_user_can_access_project_map()
    {
        $user = User::factory()->create([
            'email' => 'test@example.com',
            'password' => bcrypt('password'),
        ]);

        $project = Project::factory()->create([
            'name' => 'Existing Project',
            'creator_id' => $user->id,
        ]);
        $project->users()->attach($user->id, ['role_in_project' => 'admin']);

        $this->browse(function (Browser $browser) use ($user, $project) {
            $browser->visit('/login')
                    ->type('email', 'test@example.com')
                    ->type('password', 'password')
                    ->press('LOG IN')
                    ->visit("/projects/{$project->id}/map")
                    ->assertSee('Existing Project');
        });
    }

    public function test_user_can_view_dashboard()
    {
        $user = User::factory()->create([
            'email' => 'test@example.com',
            'password' => bcrypt('password'),
        ]);

        $this->browse(function (Browser $browser) use ($user) {
            $browser->visit('/login')
                    ->type('email', 'test@example.com')
                    ->type('password', 'password')
                    ->press('LOG IN')
                    ->assertPathIs('/dashboard')
                    ->assertSee('Proyectos')
                    ->assertSee('Tareas')
                    ->assertSee('Incidencias');
        });
    }
}