<?php

namespace Tests\Unit\Models;

use App\Models\Project;
use App\Models\ProjectStatus;
use App\Models\ProjectType;
use App\Services\ProjectService;
use App\Services\ProjectStatusService;
use Database\Seeders\ProjectStatusSeeder;
use Database\Seeders\ProjectTypeSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ProjectModelTest extends TestCase
{
    use RefreshDatabase;

    // 3.1.22 Unit test: Project status state machine
    public function test_project_status_state_machine()
    {
        $statusService = app(ProjectStatusService::class);

        $this->assertContains('SOW Approval', $statusService->getValidTransitions('Pre-sales'));
    }

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

        $service = app(ProjectService::class);

        $preSales = ProjectStatus::where('name', 'Pre-sales')->firstOrFail();
        $sowApproval = ProjectStatus::where('name', 'SOW Approval')->firstOrFail();
        $type = ProjectType::firstOrFail();

        $project = Project::factory()->create([
            'status_id' => $preSales->id,
            'type_id' => $type->id,
        ]);

        $updated = $service->transitionStatus($project, $sowApproval->id);

        $this->assertSame($sowApproval->id, $updated->status_id);
        $this->assertSame('SOW Approval', $updated->status->name);
    }

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

        $service = app(ProjectService::class);

        $preSales = ProjectStatus::where('name', 'Pre-sales')->firstOrFail();
        $inProgress = ProjectStatus::where('name', 'In Progress')->firstOrFail();
        $type = ProjectType::firstOrFail();

        $project = Project::factory()->create([
            'status_id' => $preSales->id,
            'type_id' => $type->id,
        ]);

        $this->expectException(\RuntimeException::class);
        $service->transitionStatus($project, $inProgress->id);
    }
}
