<?php

namespace Tests\Feature;

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

class RiskRegisterTest extends TestCase
{
    use RefreshDatabase;

    /** @test */
    public function it_can_create_a_risk_register()
    {
        // Create a user first (required for project charter)
        $user = User::factory()->create();
        $this->actingAs($user);

        // Create a project charter
        $charter = ProjectCharter::factory()->create();

        // Create a risk register
        $riskRegister = RiskRegister::create([
            'charter_id' => $charter->id,
            'incident_likelihood' => 'High',
            'impact_level' => 'Critical',
            'impact_on_cost' => 'Significant',
            'impact_on_time' => 'Delay expected',
            'mitigation_plan' => 'Implement backup procedures',
            'contingency_plan' => 'Switch to alternative approach',
            'financial_contingency' => 'Allocate additional budget',
            'technical_contingency' => 'Use proven technology stack',
        ]);

        $this->assertDatabaseHas('risk_registers', [
            'charter_id' => $charter->id,
            'incident_likelihood' => 'High',
            'impact_level' => 'Critical',
        ]);

        // Test relationship
        $this->assertEquals($charter->id, $riskRegister->charter->id);
        $this->assertEquals($riskRegister->id, $charter->riskRegister->id);
    }

    /** @test */
    public function it_creates_risk_register_with_nullable_fields()
    {
        $user = User::factory()->create();
        $this->actingAs($user);

        $charter = ProjectCharter::factory()->create();

        // Create risk register with only charter_id
        $riskRegister = RiskRegister::create([
            'charter_id' => $charter->id,
        ]);

        $this->assertDatabaseHas('risk_registers', [
            'charter_id' => $charter->id,
            'incident_likelihood' => null,
            'impact_level' => null,
            'impact_on_cost' => null,
            'impact_on_time' => null,
            'mitigation_plan' => null,
            'contingency_plan' => null,
            'financial_contingency' => null,
            'technical_contingency' => null,
        ]);
    }

    /** @test */
    public function it_enforces_unique_charter_id_constraint()
    {
        $user = User::factory()->create();
        $this->actingAs($user);

        $charter = ProjectCharter::factory()->create();

        // Create first risk register
        RiskRegister::create(['charter_id' => $charter->id]);

        // Attempt to create second risk register with same charter_id should fail
        $this->expectException(\Illuminate\Database\QueryException::class);
        RiskRegister::create(['charter_id' => $charter->id]);
    }
}
