<?php

namespace App\Repositories\Eloquent;

use App\Models\Professional;
use App\Models\User;

class UserManagementRepository
{
    public function paginate(array $filters = [])
    {
        return User::with(['profile', 'role', 'professional.profession'])
            ->when($filters['q'] ?? null, fn ($query, $term) => $query->where(fn ($search) => $search
                ->where('email', 'like', "%{$term}%")
                ->orWhere('uuid', 'like', "%{$term}%")
                ->orWhereHas('profile', fn ($profile) => $profile->where('full_name', 'like', "%{$term}%"))))
            ->when($filters['type'] ?? null, fn ($query, $type) => $query->whereHas('role', fn ($role) => $role->where('name', ucfirst($type))))
            ->when($filters['status'] ?? null, fn ($query, $status) => $query->where('status', $status))
            ->latest()->paginate(10)->withQueryString();
    }

    public function stats(): array
    {
        return [
            'total' => User::count(),
            'unverified' => User::where('verified', false)->count(),
            'experts' => Professional::where('status', 'approved')->whereHas('user', fn ($query) => $query->where('status', 'active'))->count(),
        ];
    }

    public function update(User $user, array $data): User
    {
        $user->update($data);

        return $user->refresh();
    }
}
