<?php

namespace Tests\Feature\Middleware;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use App\Models\User;
use Illuminate\Support\Facades\Route;
use Tests\TestCase;

class RequirePermissionMiddlewareTest extends TestCase
{
    use RefreshDatabase;

    public function test_denies_when_missing_permission(): void
    {
        Route::middleware('perm:edit_students')->get('/test-perm', fn () => 'ok');

        $user = User::query()->create([
            'firstname' => 'No',
            'lastname' => 'Perm',
            'email' => 'noperm@example.com',
            'cellphone' => '5555555555',
            'address_street' => '123 Main',
            'city' => 'City',
            'state' => 'CT',
            'zip' => '12345',
            'accept_school_policy' => 1,
            'status' => 'Active',
            'password' => 'hashed',
            'semester' => 'Fall',
        ]);

        $response = $this->actingAs($user)->get('/test-perm', ['Accept' => 'application/json']);

        $response->assertStatus(403);
    }

    public function test_allows_when_permission_assigned(): void
    {
        $permissionId = DB::table('permissions')->insertGetId([
            'name' => 'edit_students',
            'description' => 'Edit students',
        ]);

        $roleId = DB::table('roles')->insertGetId([
            'name' => 'admin',
            'priority' => 1,
        ]);

        $user = User::query()->create([
            'firstname' => 'Has',
            'lastname' => 'Perm',
            'email' => 'hasperm@example.com',
            'cellphone' => '5555555555',
            'address_street' => '123 Main',
            'city' => 'City',
            'state' => 'CT',
            'zip' => '12345',
            'accept_school_policy' => 1,
            'status' => 'Active',
            'password' => 'hashed',
            'semester' => 'Fall',
        ]);

        DB::table('user_roles')->insert([
            'user_id' => $user->id,
            'role_id' => $roleId,
        ]);

        DB::table('role_permissions')->insert([
            'role_id' => $roleId,
            'permission_id' => $permissionId,
            'can_read' => 1,
        ]);

        Route::middleware('perm:edit_students')->get('/test-perm-ok', fn () => 'ok');

        $response = $this->actingAs($user)->get('/test-perm-ok');

        $response->assertOk();
        $response->assertSee('ok');
    }
}
