<?php

namespace Tests\Unit\Policies;

use App\Models\Project;
use App\Models\User;
use App\Policies\ProjectPolicy;
use Database\Seeders\ProjectStatusSeeder;
use Database\Seeders\ProjectTypeSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ProjectPolicyTest extends TestCase
{
    use RefreshDatabase;

    // 3.1.23 Unit test: ProjectPolicy ownership checks
    public function test_project_policy_authorization()
    {
        $this->seed([ProjectStatusSeeder::class, ProjectTypeSeeder::class]);

        $policy = new ProjectPolicy;
        $roles = ['developer', 'manager', 'superuser'];

        foreach ($roles as $role) {
            $user = User::factory()->create(['role' => $role]);
            $project = Project::factory()->create();

            $this->assertTrue($policy->viewAny($user));
            $this->assertTrue($policy->view($user, $project));
        }
    }

    public function test_superuser_can_manage_all_projects()
    {
        $this->seed([ProjectStatusSeeder::class, ProjectTypeSeeder::class]);

        $policy = new ProjectPolicy;
        $user = User::factory()->create(['role' => 'superuser']);
        $project = Project::factory()->create();

        $this->assertTrue($policy->create($user));
        $this->assertTrue($policy->update($user, $project));
        $this->assertTrue($policy->delete($user, $project));
    }

    public function test_manager_can_edit_own_projects()
    {
        $this->seed([ProjectStatusSeeder::class, ProjectTypeSeeder::class]);

        $policy = new ProjectPolicy;
        $user = User::factory()->create(['role' => 'manager']);
        $project = Project::factory()->create();

        $this->assertTrue($policy->create($user));
        $this->assertTrue($policy->update($user, $project));
        $this->assertTrue($policy->delete($user, $project));
    }
}
