<?php

namespace Tests\Feature;

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

class BulkUserRoleCreationTest extends TestCase
{
    use RefreshDatabase;

    public function test_it_creates_one_thousand_parents_teachers_and_admins_through_the_api(): void
    {
        $roles = $this->seedRolesForUserCreation();
        $adminActor = $this->createAuthenticatedAdministratorActor($roles['administrator']);

        $this->actingAs($adminActor, 'api');

        $this->createUsersThroughApi('parent', (int) $roles['parent']->id, 1000);
        $this->createUsersThroughApi('teacher', (int) $roles['teacher']->id, 1000);
        $this->createUsersThroughApi('admin', (int) $roles['admin']->id, 1000);

        $this->assertSame(3000, User::query()->where('email', 'like', 'bulk_api_%')->count());
        $this->assertSame(1000, User::query()->hasRoleName('parent')->where('email', 'like', 'bulk_api_parent_%')->count());
        $this->assertSame(1000, User::query()->hasRoleName('teacher')->where('email', 'like', 'bulk_api_teacher_%')->count());
        $this->assertSame(1000, User::query()->hasRoleName('admin')->where('email', 'like', 'bulk_api_admin_%')->count());

        $this->assertDatabaseHas('users', [
            'email' => 'bulk_api_parent_0001@example.test',
            'status' => 'Active',
            'is_verified' => 1,
        ]);

        $this->assertSame(
            ['parent'],
            User::query()->where('email', 'bulk_api_parent_0001@example.test')->firstOrFail()->roleNames()
        );
        $this->assertSame(
            ['teacher'],
            User::query()->where('email', 'bulk_api_teacher_0001@example.test')->firstOrFail()->roleNames()
        );
        $this->assertSame(
            ['admin'],
            User::query()->where('email', 'bulk_api_admin_0001@example.test')->firstOrFail()->roleNames()
        );
    }

    /**
     * @return array<string, Role>
     */
    private function seedRolesForUserCreation(): array
    {
        return collect([
            'administrator' => ['name' => 'administrator', 'slug' => 'administrator', 'priority' => 5],
            'admin' => ['name' => 'admin', 'slug' => 'admin', 'priority' => 10],
            'teacher' => ['name' => 'teacher', 'slug' => 'teacher', 'priority' => 20],
            'parent' => ['name' => 'parent', 'slug' => 'parent', 'priority' => 30],
        ])->mapWithKeys(function (array $attributes, string $key): array {
            return [
                $key => Role::query()->create($attributes + [
                    'description' => ucfirst(str_replace('_', ' ', $key)),
                    'dashboard_route' => 'administrator/administratordashboard',
                    'is_active' => 1,
                ]),
            ];
        })->all();
    }

    private function createAuthenticatedAdministratorActor(Role $administratorRole): User
    {
        $adminActor = User::factory()->create([
            'email' => 'bulk-api-test-actor@example.test',
            'status' => 'Active',
            'is_verified' => 1,
        ]);

        $adminActor->roles()->attach($administratorRole->id);

        return $adminActor;
    }

    private function createUsersThroughApi(string $roleName, int $roleId, int $count): void
    {
        for ($index = 1; $index <= $count; $index++) {
            $response = $this->postJson('/api/v1/users', $this->payloadForUser($roleName, $roleId, $index));

            $response
                ->assertCreated()
                ->assertJsonPath('ok', true);
        }
    }

    /**
     * @return array<string, mixed>
     */
    private function payloadForUser(string $roleName, int $roleId, int $index): array
    {
        $number = str_pad((string) $index, 4, '0', STR_PAD_LEFT);
        $name = ucfirst($roleName);

        return [
            'firstname' => "Bulk{$name}",
            'lastname' => "User{$number}",
            'gender' => $index % 2 === 0 ? 'Female' : 'Male',
            'cellphone' => '555' . str_pad((string) $index, 7, '0', STR_PAD_LEFT),
            'email' => "bulk_api_{$roleName}_{$number}@example.test",
            'address_street' => "{$index} Test Street",
            'city' => 'Brooklyn',
            'state' => 'NY',
            'zip' => '11201',
            'accept_school_policy' => true,
            'role_id' => $roleId,
            'password' => 'password',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'school_id' => 1,
            'user_type' => 'primary',
            'status' => 'Active',
            'is_verified' => true,
            'is_suspended' => false,
        ];
    }
}
