<?php

namespace Tests\Feature;

use App\Models\Project;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Spatie\Permission\Models\Permission;
use Tests\TestCase;

class TemplatesAccessTest extends TestCase
{
    use RefreshDatabase;

    private function project(User $owner): Project
    {
        return Project::create([
            'reference' => 'TPL-1', 'name' => 'Proyecto Plantillas', 'address' => 'x',
            'lat' => 40.0, 'lng' => -3.0, 'start_date' => now()->toDateString(),
            'end_date_estimated' => now()->addMonth()->toDateString(),
            'status' => 'in_progress', 'created_by' => $owner->id,
        ]);
    }

    public function test_templates_page_requires_edit_projects_permission(): void
    {
        Permission::findOrCreate('edit projects');

        $user = User::factory()->create();              // sin permiso
        $project = $this->project($user);

        $this->actingAs($user)
            ->get(route('projects.templates', $project))
            ->assertForbidden();
    }

    public function test_templates_page_accessible_with_edit_projects_permission(): void
    {
        Permission::findOrCreate('edit projects');

        $user = User::factory()->create();
        $user->givePermissionTo('edit projects');
        $project = $this->project($user);

        $this->actingAs($user)
            ->get(route('projects.templates', $project))
            ->assertOk();
    }
}
