<?php

namespace Tests\Feature;

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

class DepartmentMemberTest extends TestCase
{
    use RefreshDatabase;

    public function test_department_index_returns_array_tree_with_department_children(): void
    {
        $admin = User::factory()->create(['status' => 'active']);
        $this->grantAdminRole($admin);
        $department = Department::create([
            'name' => 'فناوری اطلاعات',
            'type' => 'department',
            'is_active' => true,
        ]);
        Department::create([
            'name' => 'زیرساخت',
            'type' => 'unit',
            'parent_id' => $department->id,
            'is_active' => true,
        ]);

        $token = $admin->createToken('api-token')->plainTextToken;

        $this->withToken($token)
            ->getJson('/api/departments')
            ->assertOk()
            ->assertJsonPath('data.0.name', 'فناوری اطلاعات')
            ->assertJsonPath('data.0.children.0.name', 'زیرساخت')
            ->assertJsonPath('flat.1.parent_id', $department->id);
    }

    public function test_authenticated_user_can_add_member_to_department(): void
    {
        $admin = User::factory()->create(['status' => 'active']);
        $this->grantAdminRole($admin);
        $member = User::factory()->create(['status' => 'active']);
        $department = Department::create([
            'name' => 'دپارتمان محصول',
            'type' => 'department',
            'is_active' => true,
        ]);

        $token = $admin->createToken('api-token')->plainTextToken;

        $this->withToken($token)
            ->postJson("/api/departments/{$department->id}/members", [
                'user_id' => $member->id,
                'role_in_team' => 'طراح محصول',
                'is_primary' => true,
            ])
            ->assertOk()
            ->assertJsonPath('success', true);

        $this->assertDatabaseHas('department_user', [
            'department_id' => $department->id,
            'user_id' => $member->id,
            'role_in_team' => 'طراح محصول',
            'is_primary' => true,
        ]);
        $this->assertDatabaseHas('users', [
            'id' => $member->id,
            'department_id' => $department->id,
            'department' => 'دپارتمان محصول',
        ]);
    }
}
