<?php

namespace Tests\Concerns;

use App\Models\Configuration;
use App\Models\Role;
use App\Models\SchoolYear;
use App\Models\User;

trait CreatesApiTestUsers
{
    protected function seedApiTestConfig(string $schoolYear = '2025-2026', string $semester = 'Fall'): void
    {
        if (class_exists(Configuration::class)) {
            Configuration::query()->updateOrCreate(['config_key' => 'school_year'], ['config_value' => $schoolYear]);
            Configuration::query()->updateOrCreate(['config_key' => 'semester'], ['config_value' => $semester]);
        }

        if (class_exists(SchoolYear::class)) {
            SchoolYear::query()->updateOrCreate(
                ['name' => $schoolYear],
                [
                    'start_date' => '2025-09-01',
                    'end_date' => '2026-06-30',
                    'status' => SchoolYear::STATUS_ACTIVE,
                    'is_current' => true,
                ]
            );
        }
    }

    /**
     * @return array<string, Role>
     */
    protected function seedApiRoles(): array
    {
        $roles = [
            'administrator' => ['priority' => 1, 'dashboard_route' => 'administrator/administratordashboard'],
            'admin' => ['priority' => 2, 'dashboard_route' => 'administrator/administratordashboard'],
            'teacher' => ['priority' => 3, 'dashboard_route' => 'teacher/classes'],
            'parent' => ['priority' => 4, 'dashboard_route' => 'parents/profile'],
            'student' => ['priority' => 5, 'dashboard_route' => 'student/dashboard'],
        ];

        $created = [];
        foreach ($roles as $name => $attributes) {
            $created[$name] = Role::query()->updateOrCreate(
                ['name' => $name],
                [
                    'slug' => $name,
                    'description' => ucfirst($name),
                    'priority' => $attributes['priority'],
                    'dashboard_route' => $attributes['dashboard_route'],
                    'is_active' => 1,
                ]
            );
        }

        return $created;
    }

    protected function createApiUserWithRole(string $roleName = 'administrator', array $overrides = []): User
    {
        $roles = $this->seedApiRoles();
        $this->seedApiTestConfig();

        $user = User::factory()->create(array_merge([
            'status' => 'Active',
            'is_verified' => 1,
            'is_suspended' => 0,
            'email' => $roleName . '-api-test-' . str_replace('.', '', uniqid('', true)) . '@example.test',
        ], $overrides));

        $role = $roles[$roleName] ?? Role::query()->where('name', $roleName)->firstOrFail();
        $user->roles()->syncWithoutDetaching([$role->id]);

        return $user->fresh() ?? $user;
    }

    protected function actingAsApiAdministrator(): User
    {
        $user = $this->createApiUserWithRole('administrator');
        $this->actingAs($user, 'api');

        return $user;
    }

    /**
     * @return array<string, mixed>
     */
    protected function validUserPayload(int $roleId, array $overrides = []): array
    {
        $unique = str_replace('.', '', uniqid('', true));

        return array_merge([
            'firstname' => 'Api',
            'lastname' => 'Coverage',
            'gender' => 'Male',
            'cellphone' => '5551234567',
            'email' => "api.coverage.$unique@example.test",
            'address_street' => '1 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,
        ], $overrides);
    }
}
