<?php

namespace Tests\Feature;

use App\Models\Central\Company;
use App\Models\Central\Plan;
use App\Services\Ai\AiAssistantService;
use App\Tenancy\TenantManager;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class AiModelSelectorTest extends TestCase
{
    use RefreshDatabase;

    public function test_default_model_when_no_override(): void
    {
        $svc = app(AiAssistantService::class);
        $company = $this->makeCompany(['ai' => ['claude_key' => 'sk']]);

        $this->assertEquals('claude-sonnet-4-6', $svc->modelFor('claude', $company));
        $this->assertEquals('gpt-4o-mini', $svc->modelFor('gpt', $company));
        $this->assertEquals('gemini-1.5-flash', $svc->modelFor('gemini', $company));
    }

    public function test_tenant_override_wins(): void
    {
        $svc = app(AiAssistantService::class);
        $company = $this->makeCompany([
            'ai' => [
                'claude_key' => 'sk',
                'models' => [
                    'claude' => 'claude-opus-4-7',
                    'gpt' => 'gpt-4o',
                ],
            ],
        ]);

        $this->assertEquals('claude-opus-4-7', $svc->modelFor('claude', $company));
        $this->assertEquals('gpt-4o', $svc->modelFor('gpt', $company));
        // Provider without override → default.
        $this->assertEquals('gemini-1.5-flash', $svc->modelFor('gemini', $company));
    }

    public function test_unknown_provider_falls_back(): void
    {
        $svc = app(AiAssistantService::class);
        $company = $this->makeCompany([]);
        $this->assertEquals('claude-sonnet-4-6', $svc->modelFor('xyz', $company));
    }

    public function test_options_dictionary_keys_match_defaults(): void
    {
        foreach (AiAssistantService::MODEL_DEFAULTS as $provider => $default) {
            $this->assertArrayHasKey(
                $default,
                AiAssistantService::MODEL_OPTIONS[$provider],
                "default '$default' for $provider is not in MODEL_OPTIONS"
            );
        }
    }

    private function makeCompany(array $settings): Company
    {
        $plan = Plan::firstOrCreate(['slug' => 'test'], ['name' => 'T', 'price' => 0, 'features' => []]);
        $company = Company::create([
            'plan_id' => $plan->id, 'slug' => 'mdl-' . uniqid(),
            'name' => 'Model Co', 'status' => 'active', 'settings' => $settings,
        ]);
        app(TenantManager::class)->setCurrent($company);
        return $company;
    }
}
