<?php

namespace App\Http\Controllers\Api\V1\Admin\User;

use App\Models\AdminUser;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Support\AdminApiList;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Support\AdminUserApiPresenter;

/** GET /api/v1/admin/admin-users */
final class AdminUserIndexController extends Controller
{
    public function __invoke(Request $request): JsonResponse
    {
        $p = AdminApiList::readPaging($request);
        $keyword = trim((string) $request->query('keyword', ''));

        $q = AdminUser::query()
            ->with(['roles'])
            ->whereNotExists(static function ($sub): void {
                $sub->select(DB::raw(1))
                    ->from('admin_user_agents as uag')
                    ->whereColumn('uag.admin_user_id', 'admin_users.id');
            })
            ->orderByDesc('id');

        if ($keyword !== '') {
            $q->where(function ($sub) use ($keyword): void {
                $sub->where('username', 'like', '%'.$keyword.'%')
                    ->orWhere('name', 'like', '%'.$keyword.'%')
                    ->orWhere('email', 'like', '%'.$keyword.'%');
            });
        }

        $paginator = $q->paginate($p['perPage'], ['*'], 'page', $p['page']);

        return AdminApiList::json($paginator, fn (AdminUser $user): array => AdminUserApiPresenter::listItem($user));
    }
}
