<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class UserSearchController extends Controller
{
    public function __invoke(Request $request)
    {
        $q  = trim($request->get('q', ''));
        $me = auth()->user();

        if (strlen($q) < 2) {
            return response()->json([]);
        }

        $users = User::where('id', '!=', $me->id)
            ->where(function ($query) use ($q) {
                $query->where('name', 'like', "%{$q}%")
                      ->orWhere('apellidoPaterno', 'like', "%{$q}%")
                      ->orWhere('apellidoMaterno', 'like', "%{$q}%");
            })
            ->limit(8)
            ->get();

        return response()->json(
            $users->map(function (User $user) use ($me) {
                $friendship = $me->friendshipWith($user);
                $status     = $friendship?->status ?? 'none';
                $isReceiver = $friendship?->receiver_id === $me->id;

                return [
                    'id'          => $user->id,
                    'name'        => $user->name . ' ' . $user->apellidoPaterno,
                    'avatar'      => $user->profile_photo_url,
                    'profile_url' => route('social.profile', $user),
                    'chat_url'    => route('chat.show', $user),
                    'friendship'  => [
                        'status'      => $status,
                        'id'          => $friendship?->id,
                        'is_receiver' => $isReceiver,
                    ],
                ];
            })
        );
    }
}
