<?php

namespace Tests\Feature\Modules;

use App\Contracts\InstalledModuleRepositoryContract;
use App\Enums\ModuleStatus;
use App\Models\InstalledModule;
use App\Models\User;
use App\Support\InstallationState;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\File;
use Spatie\Permission\Models\Permission;
use Tests\TestCase;

class ModuleUninstallTest extends TestCase
{
    use RefreshDatabase;

    private const FINANCE_UUID = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890';

    protected function setUp(): void
    {
        parent::setUp();

        File::put(app(InstallationState::class)->lockPath(), now()->toIso8601String());

        config([
            'product_owner.license_key' => 'FREE-TEST-0000-0000',
            'product_owner.installation_id' => '00000000-0000-0000-0000-000000000001',
        ]);
        Cache::put('license.valid', true, now()->addHour());

        $this->seed(\Database\Seeders\RoleAndPermissionSeeder::class);
    }

    public function test_super_admin_can_uninstall_module(): void
    {
        $module = app(InstalledModuleRepositoryContract::class)->create([
            'module_uuid' => self::FINANCE_UUID,
            'name' => 'Finance',
            'version' => '1.0.0',
            'status' => ModuleStatus::Installed,
            'installed_at' => now(),
        ]);

        $user = User::factory()->create();
        $user->assignRole(config('permissions.super_admin_role', 'Super Admin'));

        $this->actingAs($user)
            ->delete(route('modules.destroy', $module))
            ->assertRedirect(route('modules.index'))
            ->assertSessionHas('success');

        $this->assertDatabaseMissing('installed_modules', [
            'module_uuid' => self::FINANCE_UUID,
        ]);
    }

    public function test_uninstall_revokes_module_permissions_from_roles(): void
    {
        $module = app(InstalledModuleRepositoryContract::class)->create([
            'module_uuid' => self::FINANCE_UUID,
            'name' => 'Finance',
            'version' => '1.0.0',
            'status' => ModuleStatus::Installed,
            'installed_at' => now(),
        ]);

        $user = User::factory()->create();
        $user->assignRole(config('permissions.super_admin_role', 'Super Admin'));
        $user->givePermissionTo(Permission::findByName('FINANCE_DASHBOARD_VIEW', 'web'));

        $this->actingAs($user)->delete(route('modules.destroy', $module));

        $this->assertFalse($user->fresh()->hasPermissionTo('FINANCE_DASHBOARD_VIEW'));
    }

    public function test_user_without_permission_cannot_uninstall_module(): void
    {
        $module = InstalledModule::query()->create([
            'module_uuid' => self::FINANCE_UUID,
            'name' => 'Finance',
            'version' => '1.0.0',
            'status' => ModuleStatus::Installed,
            'installed_at' => now(),
        ]);

        $user = User::factory()->create();
        $user->givePermissionTo(Permission::findByName('MODULES_VIEW', 'web'));

        $this->actingAs($user)
            ->delete(route('modules.destroy', $module))
            ->assertForbidden();

        $this->assertDatabaseHas('installed_modules', [
            'module_uuid' => self::FINANCE_UUID,
        ]);
    }

    public function test_modules_index_shows_uninstall_action_for_installed_module(): void
    {
        app(InstalledModuleRepositoryContract::class)->create([
            'module_uuid' => self::FINANCE_UUID,
            'name' => 'Finance',
            'version' => '1.0.0',
            'status' => ModuleStatus::Installed,
            'installed_at' => now(),
        ]);

        $user = User::factory()->create();
        $user->assignRole(config('permissions.super_admin_role', 'Super Admin'));

        $this->actingAs($user)
            ->get(route('modules.index'))
            ->assertOk()
            ->assertSee('Finance', false)
            ->assertSee('Uninstall', false);
    }
}
