<?php

namespace Tests\Feature\Admin;

use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class CreatePermissionTest extends TestCase
{
    public function test_admin_can_view_create_permission_form(): void
    {
        $user = User::factory()->create();
        $adminRole = Role::firstOrCreate(['slug' => 'admin'], ['name' => 'Admin']);
        DB::table('role_user')->insert([
            'role_id' => $adminRole->id,
            'user_id' => $user->id,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $this->actingAs($user);
        $this->get(route('admin.permissions.create'))
            ->assertSuccessful();
    }

    public function test_admin_creates_permission(): void
    {
        $user = User::factory()->create();
        $adminRole = Role::firstOrCreate(['slug' => 'admin'], ['name' => 'Admin']);
        DB::table('role_user')->insert([
            'role_id' => $adminRole->id,
            'user_id' => $user->id,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $this->actingAs($user);

        $this->post(route('admin.permissions.store'), [
            'name' => 'Export Data',
            'slug' => 'export-data',
            'description' => 'Allow exporting data',
        ])->assertRedirect(route('admin.index'));

        $this->assertTrue(Permission::where('slug', 'export-data')->exists());
    }
}
