<?php

declare(strict_types=1);

use Builder\Core\Models\Language;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Schema;

beforeEach(function (): void {
    Schema::dropIfExists('languages');
    Schema::create('languages', function ($table): void {
        $table->id();
        $table->string('code')->unique();
        $table->string('name');
        $table->boolean('is_active')->default(true);
        $table->boolean('is_default')->default(false);
        $table->unsignedInteger('order')->default(0);
        $table->timestamps();
    });

    Cache::forget(Language::CACHE_KEY);
});

afterEach(function (): void {
    Schema::dropIfExists('languages');
});

it('returns the language with is_default=true as defaultLocale', function (): void {
    Language::create(['code' => 'nl', 'name' => 'Nederlands', 'is_active' => true, 'is_default' => false, 'order' => 0]);
    Language::create(['code' => 'en', 'name' => 'English', 'is_active' => true, 'is_default' => true, 'order' => 1]);

    expect(Language::defaultLocale()?->code)->toBe('en');
});

it('falls back to first active language when no default is set', function (): void {
    Language::create(['code' => 'nl', 'name' => 'Nederlands', 'is_active' => true, 'is_default' => false, 'order' => 0]);
    Language::create(['code' => 'en', 'name' => 'English', 'is_active' => false, 'is_default' => false, 'order' => 1]);

    expect(Language::defaultLocale()?->code)->toBe('nl');
});

it('throws RuntimeException when no languages are configured', function (): void {
    expect(fn () => Language::defaultLocale())->toThrow(RuntimeException::class, 'No default language configured.');
});

it('invalidates cache when language is saved', function (): void {
    $lang = Language::create(['code' => 'en', 'name' => 'English', 'is_active' => true, 'is_default' => true, 'order' => 0]);

    Language::allLocales(); // populates cache

    expect(Cache::has(Language::CACHE_KEY))->toBeTrue();

    $lang->update(['name' => 'English (Updated)']);

    expect(Cache::has(Language::CACHE_KEY))->toBeFalse();
});

it('clears cache via clearCache()', function (): void {
    Language::create(['code' => 'en', 'name' => 'English', 'is_active' => true, 'is_default' => true, 'order' => 0]);
    Language::allLocales(); // populates cache

    expect(Cache::has(Language::CACHE_KEY))->toBeTrue();

    Language::clearCache();

    expect(Cache::has(Language::CACHE_KEY))->toBeFalse();
});
