<?php

namespace Tests\Feature;

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

class SettingTest extends TestCase
{
    use RefreshDatabase;

    public function test_authenticated_user_can_create_and_update_real_settings(): void
    {
        $user = User::factory()->create(['status' => 'active']);
        $this->grantAdminRole($user);
        $token = $user->createToken('api-token')->plainTextToken;

        $this->withToken($token)
            ->postJson('/api/settings', [
                'key' => 'default_task_statuses',
                'value' => ['todo', 'in_progress', 'done'],
                'group' => 'task',
                'type' => 'list',
            ])
            ->assertCreated()
            ->assertJsonPath('data.value.0', 'todo')
            ->assertJsonPath('data.type', 'list');

        $setting = Setting::where('key', 'default_task_statuses')->firstOrFail();

        $this->withToken($token)
            ->putJson("/api/settings/{$setting->id}", [
                'value' => ['todo', 'review', 'done'],
                'group' => 'task',
                'type' => 'list',
            ])
            ->assertOk()
            ->assertJsonPath('data.value.1', 'review');

        $this->assertSame(['todo', 'review', 'done'], $setting->fresh()->value);
    }

    public function test_settings_support_plain_strings_and_json_objects(): void
    {
        $user = User::factory()->create(['status' => 'active']);
        $this->grantAdminRole($user);
        $token = $user->createToken('api-token')->plainTextToken;

        $plain = Setting::create([
            'key' => 'company_name',
            'value' => 'شرکت پیشگام',
            'group' => 'general',
            'type' => 'string',
        ]);

        $this->withToken($token)
            ->getJson('/api/settings')
            ->assertOk()
            ->assertJsonFragment([
                'key' => 'company_name',
                'value' => 'شرکت پیشگام',
            ]);

        $this->withToken($token)
            ->putJson("/api/settings/{$plain->id}", [
                'value' => [
                    'host' => 'smtp.example.com',
                    'port' => '587',
                    'encryption' => 'tls',
                ],
                'group' => 'mail',
                'type' => 'json',
            ])
            ->assertOk()
            ->assertJsonPath('data.value.host', 'smtp.example.com');

        $this->assertSame('smtp.example.com', $plain->fresh()->value['host']);
    }
}
