<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Modules\Ai\Models\AiRequest;
use Illuminate\Http\Request;
use Illuminate\View\View;

/**
 * طلبات الذكاء الاصطناعي — قائمة + تفاصيل.
 */
class AiRequestController extends Controller
{
    public function index(Request $request): View
    {
        $allowedStatuses = ['pending', 'completed', 'failed'];

        $status = $request->query('status');
        $status = is_string($status) && in_array($status, $allowedStatuses, true) ? $status : null;

        $q = trim((string) $request->query('q', ''));
        if (strlen($q) > 255) {
            $q = mb_substr($q, 0, 255);
        }

        $requests = AiRequest::query()
            ->with('user')
            ->when($status, fn ($query) => $query->where('status', $status))
            ->when($q !== '', function ($query) use ($q) {
                $query->where(function ($inner) use ($q) {
                    $inner->where('prompt', 'like', "%{$q}%")
                        ->orWhere('response', 'like', "%{$q}%")
                        ->orWhereHas('user', function ($u) use ($q) {
                            $u->where('username', 'like', "%{$q}%")
                                ->orWhere('full_name', 'like', "%{$q}%");
                        });
                });
            })
            ->latest('id')
            ->paginate(20)
            ->withQueryString();

        return view('admin.ai-requests.index', [
            'requests' => $requests,
            'status' => $status,
            'q' => $q,
        ]);
    }

    public function show(AiRequest $ai_request): View
    {
        $ai_request->load('user');

        return view('admin.ai-requests.show', [
            'request' => $ai_request,
        ]);
    }
}
