<?php

namespace Tests\Feature;

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

class AdminSettingsTest extends TestCase
{
    use RefreshDatabase;

    public function test_settings_page_hides_removed_controls_and_duplicate_fields(): void
    {
        $admin = User::factory()->create(['role' => 'admin']);

        foreach ($this->singleValueSettings() as $key => $attributes) {
            Setting::create(['key' => $key, ...$attributes]);
        }

        $response = $this->actingAs($admin)->get(route('admin.settings.index'));

        $response->assertOk()
            ->assertDontSee('API preview')
            ->assertDontSee('Social Media')
            ->assertSee('name="currency_symbol"', false)
            ->assertSee('name="shipping_fee"', false)
            ->assertSee('name="telegram_bot_token"', false)
            ->assertSee('name="telegram_chat_id"', false)
            ->assertDontSee('name="currency_symbol_km"', false)
            ->assertDontSee('name="shipping_fee_km"', false)
            ->assertDontSee('name="telegram_bot_token_km"', false)
            ->assertDontSee('name="telegram_chat_id_km"', false);
    }

    public function test_single_value_settings_stay_consistent_for_api_locales(): void
    {
        $admin = User::factory()->create(['role' => 'admin']);

        foreach ($this->singleValueSettings() as $key => $attributes) {
            Setting::create(['key' => $key, ...$attributes, 'value_km' => 'stale-value']);
        }

        $values = [
            'currency_symbol' => 'USD',
            'shipping_fee' => '3.50',
            'telegram_bot_token' => 'updated-token',
            'telegram_chat_id' => 'updated-chat',
        ];

        $this->actingAs($admin)
            ->put(route('admin.settings.update'), [...$values, 'tab' => 'social'])
            ->assertRedirect(route('admin.settings.index', ['tab' => 'general']));

        foreach ($values as $key => $value) {
            $this->assertDatabaseHas('settings', [
                'key' => $key,
                'value' => $value,
                'value_km' => $value,
            ]);
        }
    }

    private function singleValueSettings(): array
    {
        return [
            'currency_symbol' => $this->setting('$', 'text', 'Currency Symbol', 1),
            'shipping_fee' => $this->setting('2.00', 'number', 'Shipping Fee ($)', 2),
            'telegram_bot_token' => $this->setting('', 'text', 'Telegram Bot Token', 3),
            'telegram_chat_id' => $this->setting('', 'text', 'Telegram Chat ID', 4),
        ];
    }

    private function setting(string $value, string $type, string $label, int $order): array
    {
        return [
            'value' => $value,
            'value_km' => $value,
            'type' => $type,
            'group' => 'general',
            'label' => $label,
            'order' => $order,
        ];
    }
}
