<?php

/* Titan © TakfeDev (MKJUEL). All Rights. */

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\AiProvider;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

class AiProviderController extends Controller
{
    public function index(): JsonResponse
    {
        $providers = AiProvider::orderBy('priority')->orderBy('provider_name')->get();
        $providers->makeHidden('api_key');
        return response()->json($providers);
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'provider_key' => 'required|string|unique:ai_providers,provider_key|regex:/^[a-z0-9_-]+$/',
            'provider_name' => 'required|string',
            'api_endpoint' => 'required|url',
            'api_key' => 'nullable|string',
            'default_model' => 'required|string',
            'notes' => 'nullable|string',
            'priority' => 'required|integer',
            'is_enabled' => 'boolean',
        ]);

        AiProvider::create($data);
        return response()->json(['message' => 'AI Provider created successfully.'], 201);
    }
    
    public function update(Request $request, AiProvider $aiProvider): JsonResponse
    {
        $data = $request->validate([
            'provider_name' => 'required|string',
            'api_endpoint' => 'required|url',
            'api_key' => 'nullable|string',
            'default_model' => 'required|string',
            'notes' => 'nullable|string',
            'priority' => 'required|integer',
            'is_enabled' => 'boolean',
        ]);

        if (!$request->filled('api_key')) {
            unset($data['api_key']);
        }
        
        if ($data['is_enabled'] === false) {
            $data['is_active'] = false;
        }

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

    public function destroy(AiProvider $aiProvider): JsonResponse
    {
        if ($aiProvider->is_active) {
            return response()->json(['message' => 'Cannot delete the active provider.'], 422);
        }
        $aiProvider->delete();
        return response()->json(['message' => 'AI Provider deleted.']);
    }

    public function setActive(AiProvider $aiProvider): JsonResponse
    {
        if (!$aiProvider->is_enabled) {
            return response()->json(['message' => 'Cannot activate a disabled provider.'], 422);
        }

        DB::transaction(function () use ($aiProvider) {
            AiProvider::query()->update(['is_active' => false]);
            $aiProvider->update(['is_active' => true]);
        });
        
        return response()->json(['message' => "{$aiProvider->provider_name} is now the active provider."]);
    }
}