<?php

namespace Tests\Feature;

use App\Models\Setting;
use App\Models\User;
use App\Providers\AppServiceProvider;
use Database\Seeders\RolesAndAdminSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ConfigurationsTest extends TestCase
{
    use RefreshDatabase;

    public function test_setting_encryption_roundtrip(): void
    {
        Setting::put('paystack_secret_key', 'sk_live_supersecret', true);

        $this->assertSame('sk_live_supersecret', Setting::get('paystack_secret_key'));

        // stored value in the DB must not be the plaintext
        $row = Setting::where('key', 'paystack_secret_key')->first();
        $this->assertTrue((bool) $row->encrypted);
        $this->assertNotSame('sk_live_supersecret', $row->value);
    }

    public function test_mail_settings_apply_to_runtime_config(): void
    {
        Setting::put('mail_mailer', 'smtp');
        Setting::put('mail_from_address', 'hello@moneywise.co.ke');
        Setting::put('smtp_host', 'smtp.example.com');
        Setting::put('smtp_port', '587');
        Setting::put('smtp_password', 'secretpass', true);
        Setting::put('smtp_encryption', 'tls');

        // Re-run the provider boot (as a fresh request would)
        (new AppServiceProvider($this->app))->boot();

        $this->assertSame('smtp', config('mail.default'));
        $this->assertSame('smtp.example.com', config('mail.mailers.smtp.host'));
        $this->assertSame('secretpass', config('mail.mailers.smtp.password'));
        $this->assertSame('hello@moneywise.co.ke', config('mail.from.address'));
    }

    public function test_configurations_page_renders_for_admin(): void
    {
        $this->seed(RolesAndAdminSeeder::class);
        $admin = User::where('email', 'admin@moneywise.co.ke')->firstOrFail();

        $this->actingAs($admin)->get('/admin/configurations')->assertSuccessful();
    }
}
