<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Models\Conversation;
use App\Services\AnthropicService;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class ConversationController extends Controller
{
    public function index(Request $request)
    {
        $conversations = auth()->user()
            ->conversations()
            ->orderByDesc('updated_at')
            ->get();

        $requestedId = $request->integer('conversation');

        $conversation = null;
        if ($requestedId) {
            $conversation = $conversations->firstWhere('id', $requestedId);
        }
        if (! $conversation) {
            $conversation = $conversations->first();
        }

        if ($conversation) {
            $conversation->load(['messages' => function ($query) {
                $query->orderBy('id');
            }, 'messages.attachments']);
        }

        return view('chat.index', [
            'conversations' => $conversations,
            'conversation' => $conversation,
            'models' => AnthropicService::availableModels(),
            'defaultModel' => AnthropicService::defaultModel(),
        ]);
    }

    public function store(Request $request)
    {
        $models = AnthropicService::availableModels();

        $validated = $request->validate([
            'model' => ['nullable', 'string', 'in:' . implode(',', array_keys($models))],
        ]);

        $model = $validated['model'] ?? AnthropicService::defaultModel();

        $conversation = Conversation::create([
            'user_id' => auth()->id(),
            'title' => null,
            'model' => $model,
        ]);

        return redirect()->route('chat.index', ['conversation' => $conversation->id]);
    }

    public function update(Request $request, Conversation $conversation)
    {
        $this->authorizeOwner($conversation);

        $validated = $request->validate([
            'title' => ['required', 'string', 'max:255'],
        ]);

        $conversation->update(['title' => $validated['title']]);

        return redirect()->back();
    }

    public function destroy(Conversation $conversation)
    {
        $this->authorizeOwner($conversation);

        $conversation->delete();

        return redirect()->route('chat.index');
    }

    public function export(Conversation $conversation)
    {
        $this->authorizeOwner($conversation);

        $conversation->load(['messages' => function ($query) {
            $query->orderBy('id');
        }]);

        $title = $conversation->title ?? 'Conversation';

        $md = '# ' . $title . "\n\n";

        foreach ($conversation->messages as $message) {
            $label = $message->role === 'user' ? '**Vous :**' : '**Assistant :**';
            $md .= $label . "\n\n";
            $md .= $message->content . "\n\n";
        }

        $filename = Str::slug($conversation->title ?? 'conversation') . '.md';

        return response()->streamDownload(function () use ($md) {
            echo $md;
        }, $filename, ['Content-Type' => 'text/markdown']);
    }

    private function authorizeOwner(Conversation $c): void
    {
        abort_unless($c->user_id === auth()->id(), 403);
    }
}
