<?php

namespace Tests\Feature\Api\V1\Ui;

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

class UiControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_style_requires_auth(): void
    {
        $response = $this->postJson('/api/v1/ui/style', [
            'accent' => 'blue',
        ]);

        $response->assertStatus(401);
    }

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

        $response = $this->postJson('/api/v1/ui/style', [
            'accent' => 'blue',
            'menu' => 'custom',
            'menu_bg' => '#112233',
            'menu_text' => '#ffffff',
            'menu_mode' => 'dark',
        ]);

        $response->assertOk();
        $this->assertDatabaseHas('user_preferences', [
            'user_id' => $user->id,
            'style_color' => 'blue',
            'menu_color' => 'custom',
        ]);
    }

    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;
    }
}
