<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AiIntegration;
use App\Services\ClaudePlanAnalyzer;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
use RuntimeException;
use Throwable;

class AiIntegrationController extends Controller
{
    public function show(): Response
    {
        $integration = AiIntegration::query()->firstOrCreate(
            ['provider' => 'anthropic'],
            ['model' => 'claude-sonnet-5'],
        );

        return Inertia::render('admin/ai-settings', [
            'integration' => [
                'enabled' => $integration->enabled,
                'model' => $integration->model,
                'hasApiKey' => filled($integration->api_key),
                'maskedKey' => filled($integration->api_key) ? '••••••••'.substr((string) $integration->api_key, -4) : null,
                'lastTestedAt' => $integration->last_tested_at?->toIso8601String(),
                'lastStatus' => $integration->last_status,
            ],
            'models' => ClaudePlanAnalyzer::MODELS,
        ]);
    }

    public function update(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'enabled' => ['required', 'boolean'],
            'model' => ['required', 'string', 'in:'.implode(',', ClaudePlanAnalyzer::MODELS)],
            'api_key' => ['nullable', 'string', 'starts_with:sk-ant-', 'max:255'],
        ]);
        $integration = AiIntegration::query()->firstOrCreate(['provider' => 'anthropic']);
        $integration->enabled = $validated['enabled'];
        $integration->model = $validated['model'];

        if (filled($validated['api_key'] ?? null)) {
            $integration->api_key = $validated['api_key'];
            $integration->last_status = null;
            $integration->last_tested_at = null;
        }

        $integration->save();

        return back()->with('success', 'Configuración de Claude guardada.');
    }

    public function test(ClaudePlanAnalyzer $analyzer): JsonResponse
    {
        try {
            $message = $analyzer->test();
            AiIntegration::query()->where('provider', 'anthropic')->update([
                'last_tested_at' => now(),
                'last_status' => 'connected',
            ]);

            return response()->json(['message' => $message]);
        } catch (Throwable $exception) {
            report($exception);
            AiIntegration::query()->where('provider', 'anthropic')->update([
                'last_tested_at' => now(),
                'last_status' => 'failed',
            ]);

            return response()->json([
                'message' => $exception instanceof RuntimeException
                    ? $exception->getMessage()
                    : 'No fue posible verificar la conexión con Claude.',
            ], 422);
        }
    }
}
