<?php

namespace App\Http\Controllers\Api;

use App\Core\Http\Controllers\BaseApiController;
use App\Models\Conversation;
use App\Models\ConversationMessage;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ConversationController extends BaseApiController
{
    public function index(Request $request): JsonResponse
    {
        $user = $request->user();
        $perPage = (int) min(40, max(5, (int) $request->query('per_page', 15)));

        $page = Conversation::query()
            ->where('user_id', $user->id)
            ->orderByDesc('last_message_at')
            ->orderByDesc('id')
            ->paginate($perPage);

        $items = collect($page->items())->map(fn (Conversation $c) => [
            'id' => $c->id,
            'title' => $c->title,
            'last_message_at' => $c->last_message_at?->toIso8601String(),
            'created_at' => $c->created_at?->toIso8601String(),
        ])->values()->all();

        return $this->successResponse('OK', [
            'items' => $items,
            'meta' => [
                'current_page' => $page->currentPage(),
                'last_page' => $page->lastPage(),
                'per_page' => $page->perPage(),
                'total' => $page->total(),
            ],
        ]);
    }

    public function messages(Request $request, int $conversation): JsonResponse
    {
        $user = $request->user();
        $c = Conversation::query()->where('user_id', $user->id)->whereKey($conversation)->first();
        if ($c === null) {
            return $this->errorResponse('المحادثة غير موجودة.', [], 404);
        }

        $perPage = (int) min(100, max(10, (int) $request->query('per_page', 50)));
        $p = ConversationMessage::query()
            ->where('conversation_id', $c->id)
            ->orderBy('id')
            ->paginate($perPage);

        $items = collect($p->items())->map(fn (ConversationMessage $m) => [
            'id' => $m->id,
            'role' => $m->role,
            'content' => $m->content,
            'created_at' => $m->created_at?->toIso8601String(),
        ])->values()->all();

        return $this->successResponse('OK', [
            'conversation' => [
                'id' => $c->id,
                'title' => $c->title,
            ],
            'items' => $items,
            'meta' => [
                'current_page' => $p->currentPage(),
                'last_page' => $p->lastPage(),
                'per_page' => $p->perPage(),
                'total' => $p->total(),
            ],
        ]);
    }

    public function updateTitle(Request $request, int $conversation): JsonResponse
    {
        $data = $request->validate([
            'title' => ['required', 'string', 'max:180'],
        ]);

        $user = $request->user();
        $c = Conversation::query()->where('user_id', $user->id)->whereKey($conversation)->first();
        if ($c === null) {
            return $this->errorResponse('المحادثة غير موجودة.', [], 404);
        }

        $c->title = $data['title'];
        $c->save();

        return $this->successResponse('تم التحديث', [
            'id' => $c->id,
            'title' => $c->title,
        ]);
    }

    public function destroy(Request $request, int $conversation): JsonResponse
    {
        $user = $request->user();
        $deleted = Conversation::query()
            ->where('user_id', $user->id)
            ->whereKey($conversation)
            ->delete();

        if ($deleted === 0) {
            return $this->errorResponse('المحادثة غير موجودة.', [], 404);
        }

        return $this->successResponse('تم الحذف', []);
    }
}
