<?php

namespace Tests\Unit\Models;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
use App\Models\TeamMember;
use App\Models\Allocation;
use App\Models\Actual;
use App\Models\Project;
use App\Models\Role;

class TeamMemberConstraintTest extends TestCase
{
    use RefreshDatabase;

    // 2.1.19 Unit test: Cannot delete with allocations constraint
    public function test_cannot_delete_team_member_with_allocations()
    {
        $role = Role::factory()->create();
        $teamMember = TeamMember::factory()->create(['role_id' => $role->id]);
        $project = Project::factory()->create();

        // Create an allocation for the team member
        Allocation::factory()->create([
            'team_member_id' => $teamMember->id,
            'project_id' => $project->id,
            'month' => '2024-01',
            'allocated_hours' => 40,
        ]);

        // Verify allocation exists
        $this->assertTrue($teamMember->fresh()->allocations()->exists());

        // Attempt to delete should be prevented by controller logic
        // This test documents the constraint behavior
        $this->assertTrue($teamMember->allocations()->exists());
    }

    public function test_cannot_delete_team_member_with_actuals()
    {
        $role = Role::factory()->create();
        $teamMember = TeamMember::factory()->create(['role_id' => $role->id]);
        $project = Project::factory()->create();

        // Create an actual for the team member
        Actual::factory()->create([
            'team_member_id' => $teamMember->id,
            'project_id' => $project->id,
            'month' => '2024-01',
            'hours_logged' => 40,
        ]);

        // Verify actual exists
        $this->assertTrue($teamMember->fresh()->actuals()->exists());

        // This test documents the constraint behavior
        $this->assertTrue($teamMember->actuals()->exists());
    }

    public function test_can_delete_team_member_without_allocations_or_actuals()
    {
        $role = Role::factory()->create();
        $teamMember = TeamMember::factory()->create(['role_id' => $role->id]);

        // Verify no allocations or actuals
        $this->assertFalse($teamMember->allocations()->exists());
        $this->assertFalse($teamMember->actuals()->exists());

        // Delete should succeed
        $teamMemberId = $teamMember->id;
        $teamMember->delete();

        $this->assertDatabaseMissing('team_members', [
            'id' => $teamMemberId,
        ]);
    }
}
