<?php

namespace Tests\Feature;

use App\Livewire\Projects\FeatureManager;
use App\Livewire\Projects\FeatureTypeManager;
use App\Livewire\Projects\ProjectFeaturesTable;
use App\Models\Feature;
use App\Models\FeatureType;
use App\Models\Layer;
use App\Models\Phase;
use App\Models\Project;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Spatie\Permission\Models\Permission;
use Tests\TestCase;

class FeatureManagementTest extends TestCase
{
    use RefreshDatabase;

    private User $user;

    private Project $project;

    private Feature $feature;

    protected function setUp(): void
    {
        parent::setUp();
        Permission::findOrCreate('edit layers');
        $this->user = User::factory()->create();
        $this->user->givePermissionTo('edit layers');

        $this->project = Project::create([
            'reference' => 'FT-1', 'name' => 'Proyecto Feat', 'address' => 'x',
            'lat' => 40.0, 'lng' => -3.0, 'start_date' => now()->toDateString(),
            'end_date_estimated' => now()->addMonth()->toDateString(),
            'status' => 'in_progress', 'created_by' => $this->user->id,
        ]);
        $this->project->users()->attach($this->user->id, ['role_in_project' => 'supervisor']);

        $phase = Phase::create(['project_id' => $this->project->id, 'name' => 'F1', 'order' => 1, 'color' => '#000', 'progress_percent' => 0]);
        $layer = Layer::create(['project_id' => $this->project->id, 'phase_id' => $phase->id, 'name' => 'Capa A', 'color' => '#111', 'uploaded_by' => $this->user->id]);
        $this->feature = Feature::create([
            'layer_id' => $layer->id, 'name' => 'Pilar 12',
            'geometry' => ['type' => 'Point', 'coordinates' => [-3.0, 40.0]],
            'progress' => 0, 'status' => 'planned', 'is_active' => true,
        ]);
    }

    // ── Catálogo de tipos ────────────────────────────────────────────────────────

    public function test_feature_type_manager_creates_a_type(): void
    {
        Livewire::actingAs($this->user)
            ->test(FeatureTypeManager::class)
            ->call('newType')
            ->set('name', 'Pilar')
            ->set('color', '#ff0000')
            ->call('save')
            ->assertHasNoErrors();

        $this->assertDatabaseHas('feature_types', ['name' => 'Pilar', 'color' => '#ff0000']);
    }

    public function test_feature_type_manager_requires_edit_layers(): void
    {
        $weak = User::factory()->create();
        Livewire::actingAs($weak)
            ->test(FeatureTypeManager::class)
            ->assertForbidden();
    }

    // ── Editor de elementos ──────────────────────────────────────────────────────

    public function test_features_table_lists_and_toggles_active(): void
    {
        Livewire::actingAs($this->user)
            ->test(ProjectFeaturesTable::class, ['projectId' => $this->project->id])
            ->assertOk()
            ->assertSee('Pilar 12')
            ->call('toggleActive', $this->feature->id);

        $this->assertFalse($this->feature->fresh()->is_active);
    }

    public function test_feature_manager_edits_name_type_and_active(): void
    {
        $type = FeatureType::create(['name' => 'Viga', 'color' => '#00ff00']);

        Livewire::actingAs($this->user)
            ->test(FeatureManager::class, ['project' => $this->project])
            ->call('editFeature', $this->feature->id)
            ->assertSet('name', 'Pilar 12')
            ->set('name', 'Pilar 12-B')
            ->set('featureTypeId', $type->id)
            ->set('isActive', false)
            ->call('save')
            ->assertHasNoErrors();

        $f = $this->feature->fresh();
        $this->assertEquals('Pilar 12-B', $f->name);
        $this->assertEquals($type->id, $f->feature_type_id);
        $this->assertFalse($f->is_active);
    }

    public function test_features_table_deletes_individual_feature(): void
    {
        Livewire::actingAs($this->user)
            ->test(ProjectFeaturesTable::class, ['projectId' => $this->project->id])
            ->call('deleteFeature', $this->feature->id);

        $this->assertDatabaseMissing('features', ['id' => $this->feature->id, 'deleted_at' => null]);
    }

    public function test_feature_manager_forbidden_without_edit_layers(): void
    {
        $weak = User::factory()->create();
        $this->project->users()->attach($weak->id, ['role_in_project' => 'viewer']);

        Livewire::actingAs($weak)
            ->test(FeatureManager::class, ['project' => $this->project])
            ->assertForbidden();
    }
}
