<?php

namespace Tests\Feature\Api\V1\Roles;

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

class RolePermissionControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_roles_index_returns_roles(): void
    {
        $user = $this->seedUser();
        $this->seedRole();
        Sanctum::actingAs($user);

        $response = $this->getJson('/api/v1/role-permissions/roles');

        $response->assertOk();
        $response->assertJsonPath('status', true);
        $this->assertNotEmpty($response->json('data.roles'));
    }

    public function test_store_role_creates_role(): void
    {
        $user = $this->seedUser();
        Sanctum::actingAs($user);

        $response = $this->postJson('/api/v1/role-permissions/roles', [
            'name' => 'coach',
            'slug' => 'coach',
            'description' => 'Coach role',
            'dashboard_route' => 'coach/dashboard',
            'priority' => 5,
            'is_active' => 1,
        ]);

        $response->assertStatus(201);
        $this->assertDatabaseHas('roles', ['name' => 'coach']);
    }

    public function test_update_role_updates_role(): void
    {
        $user = $this->seedUser();
        $roleId = $this->seedRole();
        Sanctum::actingAs($user);

        $response = $this->patchJson('/api/v1/role-permissions/roles/' . $roleId, [
            'description' => 'updated',
        ]);

        $response->assertOk();
        $this->assertDatabaseHas('roles', ['id' => $roleId, 'description' => 'updated']);
    }

    public function test_delete_role_removes_role(): void
    {
        $user = $this->seedUser();
        $roleId = $this->seedRole();
        Sanctum::actingAs($user);

        $response = $this->deleteJson('/api/v1/role-permissions/roles/' . $roleId);

        $response->assertOk();
        $this->assertDatabaseMissing('roles', ['id' => $roleId]);
    }

    public function test_users_index_returns_users_with_roles(): void
    {
        $user = $this->seedUser();
        $roleId = $this->seedRole();
        DB::table('user_roles')->insert([
            'user_id' => $user->id,
            'role_id' => $roleId,
        ]);

        Sanctum::actingAs($user);
        $response = $this->getJson('/api/v1/role-permissions/users');

        $response->assertOk();
        $response->assertJsonPath('status', true);
        $this->assertNotEmpty($response->json('data.users'));
    }

    public function test_assign_roles_updates_user_roles(): void
    {
        $user = $this->seedUser();
        $roleId = $this->seedRole();
        Sanctum::actingAs($user);

        $response = $this->postJson('/api/v1/role-permissions/users/' . $user->id . '/roles', [
            'role_ids' => [$roleId],
        ]);

        $response->assertOk();
        $this->assertDatabaseHas('user_roles', [
            'user_id' => $user->id,
            'role_id' => $roleId,
        ]);
        $this->assertDatabaseHas('staff', [
            'user_id' => $user->id,
        ]);
    }

    public function test_permissions_crud(): void
    {
        $user = $this->seedUser();
        Sanctum::actingAs($user);

        $create = $this->postJson('/api/v1/role-permissions/permissions', [
            'name' => 'manage_settings',
            'description' => 'Manage settings',
        ]);
        $create->assertStatus(201);
        $permissionId = (int) $create->json('data.permission.id');

        $show = $this->getJson('/api/v1/role-permissions/permissions/' . $permissionId);
        $show->assertOk();

        $update = $this->patchJson('/api/v1/role-permissions/permissions/' . $permissionId, [
            'description' => 'Updated',
        ]);
        $update->assertOk();

        $delete = $this->deleteJson('/api/v1/role-permissions/permissions/' . $permissionId);
        $delete->assertOk();
        $this->assertDatabaseMissing('permissions', ['id' => $permissionId]);
    }

    public function test_role_permissions_update(): void
    {
        $user = $this->seedUser();
        $roleId = $this->seedRole();
        $permissionId = $this->seedPermission();

        Sanctum::actingAs($user);
        $response = $this->putJson('/api/v1/role-permissions/roles/' . $roleId . '/permissions', [
            'permissions' => [
                $permissionId => ['create' => true, 'read' => true],
            ],
        ]);

        $response->assertOk();
        $this->assertDatabaseHas('role_permissions', [
            'role_id' => $roleId,
            'permission_id' => $permissionId,
            'can_create' => 1,
            'can_read' => 1,
        ]);
    }

    public function test_validation_rejects_invalid_role_payload(): void
    {
        $user = $this->seedUser();
        Sanctum::actingAs($user);

        $response = $this->postJson('/api/v1/role-permissions/roles', [
            'name' => 'a',
        ]);

        $response->assertStatus(422);
    }

    public function test_store_role_returns_error_on_service_exception(): void
    {
        $user = $this->seedUser();
        Sanctum::actingAs($user);

        $this->app->bind(\App\Services\Roles\RoleCrudService::class, function () {
            return new class {
                public function create(array $payload)
                {
                    throw new \RuntimeException('fail');
                }
            };
        });

        $response = $this->postJson('/api/v1/role-permissions/roles', [
            'name' => 'admin',
            'slug' => 'admin',
            'description' => 'Admin',
            'dashboard_route' => 'administrator/administratordashboard',
            'priority' => 1,
            'is_active' => 1,
        ]);

        $response->assertStatus(500);
        $response->assertJsonPath('status', false);
    }

    public function test_requires_authentication(): void
    {
        $response = $this->getJson('/api/v1/role-permissions/roles');

        $response->assertStatus(401);
    }

    private function seedUser(): User
    {
        $userId = DB::table('users')->insertGetId([
            'firstname' => 'Admin',
            'lastname' => 'User',
            'cellphone' => '9999999999',
            'email' => 'roles@example.com',
            'address_street' => '123 Street',
            'city' => 'City',
            'state' => 'ST',
            'zip' => '12345',
            'accept_school_policy' => 1,
            'password' => bcrypt('password'),
            'user_type' => 'primary',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'status' => 'Active',
        ]);

        return User::query()->findOrFail($userId);
    }

    private function seedRole(): int
    {
        return DB::table('roles')->insertGetId([
            'name' => 'admin',
            'slug' => 'admin',
            'description' => 'Admin',
            'dashboard_route' => 'administrator/administratordashboard',
            'priority' => 1,
            'is_active' => 1,
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

    private function seedPermission(): int
    {
        return DB::table('permissions')->insertGetId([
            'name' => 'manage_roles',
            'description' => 'Manage roles',
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }
}
