<?php

namespace App\Http\Controllers\API\V1;

use App\AiAgents\ProductAssistant;
use App\Http\Controllers\Controller;
use App\Http\Requests\AssistantChatRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AssistantController extends Controller
{
    public function __construct(
        private ProductAssistant $assistant
    ) {}

    public function chat(AssistantChatRequest $request): JsonResponse
    {
        $userId = Auth::check() ? Auth::id() : null;
        $sessionId = $userId ? null : $request->input('session_id', $this->generateSessionId());

        try {
            $result = $this->assistant->chat(
                message: $request->input('message'),
                sessionId: $sessionId,
                userId: $userId
            );

            return response()->json([
                'success' => true,
                'data' => [
                    'response' => $result['response'],
                    'suggestions' => $result['suggestions'],
                    'session_id' => $sessionId,
                ],
                'metadata' => $result['metadata'],
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'An error occurred while processing your request.',
                'error' => config('app.debug') ? $e->getMessage() : null,
            ], 500);
        }
    }

    public function getHistory(Request $request): JsonResponse
    {
        $userId = Auth::id();
        $sessionId = $request->query('session_id');

        if (! $userId && ! $sessionId) {
            return response()->json([
                'success' => false,
                'message' => 'Either authentication or session_id is required.',
            ], 400);
        }

        try {
            $history = $this->assistant->getHistory($userId, $sessionId);

            return response()->json([
                'success' => true,
                'data' => [
                    'history' => $history,
                    'total' => count($history),
                ],
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to retrieve chat history.',
                'error' => config('app.debug') ? $e->getMessage() : null,
            ], 500);
        }
    }

    public function clearHistory(Request $request): JsonResponse
    {
        $userId = Auth::id();
        $sessionId = $request->input('session_id');

        if (! $userId && ! $sessionId) {
            return response()->json([
                'success' => false,
                'message' => 'Either authentication or session_id is required.',
            ], 400);
        }

        try {
            $cleared = $this->assistant->clearHistory($userId, $sessionId);

            return response()->json([
                'success' => true,
                'message' => $cleared ? 'Chat history cleared successfully.' : 'No history to clear.',
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to clear chat history.',
                'error' => config('app.debug') ? $e->getMessage() : null,
            ], 500);
        }
    }

    public function getSuggestions(Request $request): JsonResponse
    {
        $suggestions = [
            'Show me products under [price]',
            'Find the best deals today',
            'Recommend products in [category]',
            'Compare products [id1], [id2], [id3]',
            'Tell me about product [id]',
            'What are the trending products?',
            'Find products with discounts above 20%',
            'Show me the highest-rated products',
        ];

        return response()->json([
            'success' => true,
            'data' => [
                'suggestions' => $suggestions,
                'count' => count($suggestions),
            ],
        ], 200);
    }

    protected function generateSessionId(): string
    {
        return 'sess_'.str()->random(32);
    }
}
