<?php

namespace Tests\Feature;

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

class TaskAssignmentTest extends TestCase
{
    use RefreshDatabase;

    public function test_task_can_only_be_transferred_to_an_approved_project_member(): void
    {
        $admin = User::factory()->create(['status' => 'active']);
        $this->grantAdminRole($admin);
        $token = $admin->createToken('task-assignment-test')->plainTextToken;

        $approvedMember = User::factory()->create(['status' => 'active']);
        $outsideUser = User::factory()->create(['status' => 'active']);
        $project = Project::create([
            'title' => 'پروژه انتقال مسئول',
            'project_manager_id' => $admin->id,
            'created_by' => $admin->id,
            'start_date' => now()->toDateString(),
            'end_date' => now()->addMonth()->toDateString(),
            'status' => 'in_progress',
        ]);
        $project->members()->attach($approvedMember->id);

        $task = Task::create([
            'title' => 'تسک قابل انتقال',
            'project_id' => $project->id,
            'assignee_id' => $admin->id,
            'reporter_id' => $admin->id,
            'created_by' => $admin->id,
            'status' => 'todo',
        ]);

        $this->withToken($token)
            ->putJson("/api/tasks/{$task->id}/assignee", ['assignee_id' => $approvedMember->id])
            ->assertOk()
            ->assertJsonPath('data.assignee_id', $approvedMember->id);

        $this->assertDatabaseHas('notifications', [
            'user_id' => $approvedMember->id,
            'type' => 'task_assigned',
            'notifiable_id' => $task->id,
        ]);

        $this->withToken($token)
            ->putJson("/api/tasks/{$task->id}/assignee", ['assignee_id' => $outsideUser->id])
            ->assertUnprocessable()
            ->assertJsonValidationErrors('assignee_id');

        $this->withToken($token)
            ->patchJson("/api/tasks/{$task->id}", ['assignee_id' => $outsideUser->id])
            ->assertUnprocessable()
            ->assertJsonValidationErrors('assignee_id');

        $this->assertDatabaseHas('tasks', [
            'id' => $task->id,
            'assignee_id' => $approvedMember->id,
        ]);
    }
}
