<?php

namespace Tests\Feature;

use App\Models\Setting;
use Illuminate\Http\UploadedFile;
use Tests\TestCase;

class SettingsTest extends TestCase
{
    public function test_settings_can_be_saved_without_logo(): void
    {
        $admin = $this->admin();

        $this->actingAs($admin)
            ->from(route('settings.index'))
            ->put(route('settings.update'), $this->payload())
            ->assertRedirect(route('settings.index'))
            ->assertSessionHas('success');

        $this->assertDatabaseHas('settings', [
            'key' => 'company_name',
            'value' => 'محل الاتصالات',
        ]);
    }

    public function test_settings_can_upload_and_replace_company_logo(): void
    {
        $admin = $this->admin();
        $logo = UploadedFile::fake()->image('company-logo.png', 240, 80);

        $this->actingAs($admin)
            ->from(route('settings.index'))
            ->put(route('settings.update'), $this->payload([
                'company_logo' => $logo,
            ]))
            ->assertRedirect(route('settings.index'))
            ->assertSessionHas('success')
            ->assertSessionDoesntHaveErrors();

        $path = Setting::valueOf('company_logo');
        $this->assertNotEmpty($path);
        $this->assertFileExists(public_path($path));
        $this->assertStringStartsWith('uploads/logos/', $path);
    }

    /**
     * @param  array<string, mixed>  $overrides
     * @return array<string, mixed>
     */
    private function payload(array $overrides = []): array
    {
        return array_merge([
            'company_name' => 'محل الاتصالات',
            'company_address' => 'القاهرة',
            'company_phone' => '01000000000',
            'company_email' => '',
            'currency' => 'EGP',
            'tax_rate' => '14',
            'invoice_prefix' => 'INV',
            'default_language' => 'ar',
            'default_payment_method' => 'cash',
            'printer_type' => 'a4',
            'date_format' => 'Y-m-d',
            'timezone' => 'Africa/Cairo',
            'backup_retention_days' => 30,
            'invoice_footer' => '',
        ], $overrides);
    }
}
