<?php

declare(strict_types=1);

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AiConversation;
use App\Services\AiAssistant\AiAssistantService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class AdminAiChatController extends Controller
{
    public function __construct(
        private AiAssistantService $assistant
    ) {}

    public function index(): View
    {
        $conversations = AiConversation::query()
            ->with(['user', 'messages'])
            ->withCount('messages')
            ->orderByDesc('last_message_at')
            ->paginate(20);

        $stats = [
            'total_conversations' => AiConversation::count(),
            'total_messages' => \App\Models\AiMessage::count(),
            'active_today' => AiConversation::whereDate('last_message_at', today())->count(),
        ];

        return view('admin.ai-chat.index', compact('conversations', 'stats'));
    }

    public function show(string $ulid): View
    {
        $conversation = AiConversation::where('ulid', $ulid)
            ->with(['user', 'messages'])
            ->firstOrFail();

        $messages = $conversation->messages;

        return view('admin.ai-chat.show', compact('conversation', 'messages'));
    }

    public function create(): RedirectResponse
    {
        $conversation = AiConversation::create([
            'user_id' => auth()->id(),
            'ulid' => (string) \Illuminate\Support\Str::ulid(),
            'title' => null,
            'last_message_at' => now(),
        ]);

        return redirect()->route('admin.ai-chat.show', $conversation->ulid);
    }

    public function store(Request $request, string $ulid): RedirectResponse
    {
        $validated = $request->validate([
            'message' => 'required|string|max:5000',
        ]);

        try {
            $response = $this->assistant->chat(
                $validated['message'],
                $ulid,
                auth()->user()
            );

            return back()->with('success', 'Message sent successfully');
        } catch (\Throwable $e) {
            return back()->with('error', 'Failed to send message: '.$e->getMessage());
        }
    }

    public function delete(string $ulid): RedirectResponse
    {
        $conversation = AiConversation::where('ulid', $ulid)->firstOrFail();

        $conversation->delete();

        return redirect()->route('admin.ai-chat.index')
            ->with('success', 'Conversation deleted successfully');
    }

    public function stream(Request $request, string $ulid)
    {
        $validated = $request->validate([
            'message' => 'required|string|max:5000',
        ]);

        return $this->assistant->stream(
            $validated['message'],
            $ulid,
            auth()->user()
        );
    }
}
