<?php

namespace Tests\Feature\Api\V1\Settings;

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

class ConfigurationControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_index_returns_configs(): void
    {
        DB::table('configuration')->insert([
            'config_key' => 'school_year',
            'config_value' => '2025-2026',
        ]);

        Sanctum::actingAs($this->seedUser());
        $response = $this->getJson('/api/v1/configuration');

        $response->assertOk();
        $response->assertJson(['ok' => true]);
        $this->assertNotEmpty($response->json('configs'));
    }

    public function test_store_creates_config(): void
    {
        Sanctum::actingAs($this->seedUser());
        $response = $this->postJson('/api/v1/configuration', [
            'config_key' => 'semester',
            'config_value' => 'Fall',
        ]);

        $response->assertStatus(201);
        $this->assertDatabaseHas('configuration', [
            'config_key' => 'semester',
            'config_value' => 'Fall',
        ]);
    }

    private function seedUser(): User
    {
        $userId = DB::table('users')->insertGetId([
            'firstname' => 'Admin',
            'lastname' => 'User',
            'cellphone' => '3333333333',
            'email' => 'config@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);
    }
}
