<?php

namespace Tests\Feature\Api\V1\Settings;

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

class SettingsControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_index_requires_admin(): void
    {
        $user = $this->createUser('teacher');
        Sanctum::actingAs($user);

        $response = $this->getJson('/api/v1/settings');

        $response->assertForbidden();
    }

    public function test_index_returns_settings(): void
    {
        $admin = $this->createUser('admin');
        Sanctum::actingAs($admin);

        $response = $this->getJson('/api/v1/settings');

        $response->assertOk();
        $response->assertJsonStructure(['data' => ['settings' => ['site_name', 'administrator_email', 'timezone']]]);
    }

    public function test_update_validation_rejects_bad_email(): void
    {
        $admin = $this->createUser('admin');
        Sanctum::actingAs($admin);

        $response = $this->patchJson('/api/v1/settings', [
            'administrator_email' => 'not-an-email',
        ]);

        $response->assertStatus(422);
        $response->assertJsonStructure(['message', 'errors']);
    }

    public function test_update_persists_settings(): void
    {
        $admin = $this->createUser('admin');
        Sanctum::actingAs($admin);

        $response = $this->patchJson('/api/v1/settings', [
            'site_name' => 'Alrahma',
            'timezone' => 'UTC',
            'administrator_email' => 'admin@example.com',
        ]);

        $response->assertOk();
        $this->assertDatabaseHas('settings', [
            'name' => 'Alrahma',
            'timezone' => 'UTC',
        ]);
        $this->assertDatabaseHas('configuration', [
            'config_key' => 'administrator_email',
            'config_value' => 'admin@example.com',
        ]);
    }

    private function createUser(string $roleName): User
    {
        $roleId = DB::table('roles')->insertGetId([
            'name' => $roleName,
            'priority' => 1,
            'is_active' => 1,
        ]);

        $user = User::query()->create([
            'firstname' => 'Test',
            'lastname' => 'User',
            'email' => $roleName . '@example.com',
            'cellphone' => '5555555555',
            'address_street' => '123 Main',
            'city' => 'City',
            'state' => 'ST',
            'zip' => '12345',
            'accept_school_policy' => 1,
            'status' => 'Active',
            'password' => bcrypt('secret'),
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

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

        return $user;
    }
}
