<?php

namespace App\Http\Controllers;

use App\Models\AskAnything;
use App\Models\City;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class AskController extends Controller
{
    public function ask(Request $request): JsonResponse
    {
        $data = $request->validate([
            'question' => ['required', 'string', 'max:2000'],
            'city_id' => ['nullable', 'exists:cities,id'],
            'name' => ['nullable', 'string', 'max:255'],
            'email' => ['nullable', 'email', 'max:255'],
            'phone' => ['nullable', 'string', 'max:50'],
        ]);

        $city = $data['city_id'] ?? null ? City::find($data['city_id']) : null;

        $userMessage = $city
            ? "City: {$city->name}, {$city->country}\n\nQuestion: {$data['question']}"
            : $data['question'];

        $answer = $this->askAnthropic($userMessage);

        $record = AskAnything::create([
            'name' => $data['name'] ?? null,
            'email' => $data['email'] ?? null,
            'phone' => $data['phone'] ?? null,
            'question' => $data['question'],
            'answer' => $answer,
            'created_at' => now(),
        ]);

        return response()->json([
            'answer' => $answer,
            'id' => $record->id,
        ]);
    }

    protected function askAnthropic(string $userMessage): string
    {
        $apiKey = config('services.anthropic.api_key');

        if (! $apiKey) {
            return "iiSHEEG's assistant is not configured yet. Please set ANTHROPIC_API_KEY in your .env file.";
        }

        $response = Http::withHeaders([
            'x-api-key' => $apiKey,
            'anthropic-version' => '2023-06-01',
            'content-type' => 'application/json',
        ])->post('https://api.anthropic.com/v1/messages', [
            'model' => config('services.anthropic.model', 'claude-sonnet-4-6'),
            'max_tokens' => 500,
            'system' => 'You are iiSHEEG, a helpful assistant for the Somali diaspora. When asked about services, businesses or information in a specific city, provide helpful specific recommendations and practical guidance. Be warm, knowledgeable and concise.',
            'messages' => [
                ['role' => 'user', 'content' => $userMessage],
            ],
        ]);

        if ($response->failed()) {
            return 'Sorry, the assistant is temporarily unavailable. Please try again shortly.';
        }

        return $response->json('content.0.text') ?? 'Sorry, I could not generate an answer just now.';
    }
}
