<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\UsernameRequest;
use App\Models\User;
use App\Support\UsernamePolicy;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

final class UsernameAvailabilityController extends Controller
{
    public function __invoke(Request $request): JsonResponse
    {
        $candidate = UsernamePolicy::normalize((string) $request->query('username', ''));

        $validator = validator(
            ['username' => $candidate],
            ['username' => UsernameRequest::formatRules()]
        );

        if ($validator->fails()) {
            return response()->json([
                'available' => false,
                'normalized' => $candidate,
                'errors' => $validator->errors()->toArray(),
            ], 422);
        }

        $ignoreUserId = $request->user()?->id;
        $exists = User::query()
            ->whereRaw('LOWER(username) = ?', [$candidate])
            ->when($ignoreUserId !== null, fn ($q) => $q->where('id', '!=', (int) $ignoreUserId))
            ->exists();

        return response()->json([
            'available' => ! $exists,
            'normalized' => $candidate,
        ]);
    }
}
