<?php

namespace Tests\Feature;

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

class WellLicenseRequirementsAutoCreationTest extends TestCase
{
    use RefreshDatabase;

    public function test_well_license_auto_creates_default_requirements(): void
    {
        $user = User::factory()->create();
        $this->actingAs($user);

        $wellLicense = WellLicense::factory()->create();

        // Assert that 5 requirements were created
        $this->assertCount(5, $wellLicense->requirements);

        // Assert that all requirements have pending status
        $wellLicense->requirements->each(function ($requirement) {
            $this->assertEquals(LicenseRequirement::STATUS_PENDING, $requirement->status);
        });

        // Assert that the correct requirement names were created
        $expectedRequirements = [
            'رفع مساحي يوضح الموقع العام وموقع البئر',
            'إفصاح البئر',
            'تحليل عينة مياه البئر',
            'صك الملكية او قرار تخصيص او إفادة من امارة المركز بإن الموقع لا يوجد عليها نزاعات قبلية أو فردية',
            'صور للبئر',
        ];

        $actualRequirements = $wellLicense->requirements->pluck('name')->toArray();

        foreach ($expectedRequirements as $expected) {
            $this->assertContains($expected, $actualRequirements);
        }
    }

    public function test_well_license_requirements_are_morphed_correctly(): void
    {
        $user = User::factory()->create();
        $this->actingAs($user);

        $wellLicense = WellLicense::factory()->create();

        $wellLicense->requirements->each(function ($requirement) use ($wellLicense) {
            $this->assertEquals(WellLicense::class, $requirement->licenseable_type);
            $this->assertEquals($wellLicense->id, $requirement->licenseable_id);
            $this->assertTrue($requirement->licenseable->is($wellLicense));
        });
    }

    public function test_well_license_requirements_saved_to_database(): void
    {
        $user = User::factory()->create();
        $this->actingAs($user);

        $wellLicense = WellLicense::factory()->create();

        $this->assertDatabaseCount('license_requirements', 5);

        $wellLicense->requirements->each(function ($requirement) use ($wellLicense) {
            $this->assertDatabaseHas('license_requirements', [
                'id' => $requirement->id,
                'name' => $requirement->name,
                'status' => LicenseRequirement::STATUS_PENDING,
                'licenseable_id' => $wellLicense->id,
                'licenseable_type' => WellLicense::class,
            ]);
        });
    }
}
