<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AiProvider;
use App\Models\Setting;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Facades\Cache;

class AiProviderController extends Controller
{
    public function index()
    {
        return Inertia::render('cp/Settings/AiProviders');
    }

    public function getProviders()
    {
        $settings = [
            'ai_auto_select_enabled' => filter_var(Setting::where('key', 'ai_auto_select_enabled')->value('value') ?? true, FILTER_VALIDATE_BOOLEAN)
        ];

        // Hide the actual API keys from the frontend for security. 
        // We just need to know if it exists (is not null).
        $providers = AiProvider::orderBy('priority', 'asc')->get()->map(function ($provider) {
            $provider->has_api_key = !empty($provider->api_key);
            $provider->makeHidden('api_key');
            return $provider;
        });

        return response()->json([
            'settings' => $settings,
            'providers' => $providers
        ]);
    }

    public function saveGlobalSettings(Request $request)
    {
        $request->validate(['ai_auto_select_enabled' => 'boolean']);
        Setting::updateOrCreate(
            ['key' => 'ai_auto_select_enabled'], 
            ['value' => $request->ai_auto_select_enabled ? '1' : '0']
        );
        Cache::forget('app_settings');
        return response()->json(['message' => 'Global settings updated.']);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'provider_name' => 'required|string|max:255',
            'provider_key' => 'required|string|max:100|unique:ai_providers',
            'api_endpoint' => 'required|url',
            'api_key' => 'required|string',
            'default_model' => 'required|string',
            'priority' => 'integer',
            'notes' => 'nullable|string',
            'is_enabled' => 'boolean',
        ]);

        AiProvider::create($validated);
        return response()->json(['message' => 'Provider added successfully.']);
    }

    public function update(Request $request, AiProvider $aiProvider)
    {
        $validated = $request->validate([
            'provider_name' => 'required|string|max:255',
            'api_endpoint' => 'required|url',
            'default_model' => 'required|string',
            'priority' => 'integer',
            'notes' => 'nullable|string',
            'is_enabled' => 'boolean',
        ]);

        // Only update the API key if a new one is provided
        if ($request->filled('api_key')) {
            $validated['api_key'] = $request->api_key;
        }

        $aiProvider->update($validated);
        return response()->json(['message' => 'Provider updated successfully.']);
    }

    public function destroy(AiProvider $aiProvider)
    {
        if ($aiProvider->is_default) {
            return response()->json(['message' => 'Cannot delete the default active provider.'], 400);
        }
        $aiProvider->delete();
        return response()->json(['message' => 'Provider deleted.']);
    }

    public function setDefault(AiProvider $aiProvider)
    {
        if (!$aiProvider->is_enabled) {
            return response()->json(['message' => 'Cannot set a disabled provider as default.'], 400);
        }
        AiProvider::query()->update(['is_default' => false]);
        $aiProvider->update(['is_default' => true]);
        return response()->json(['message' => 'Active provider updated.']);
    }
}