<?php

namespace App\Actions\Fortify;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
use Laravel\Fortify\Fortify;

class AuthenticateUser
{
    /**
     * Resolve the user attempting to log in, rejecting inactive accounts.
     */
    public function __invoke(Request $request): ?User
    {
        $user = User::where(Fortify::username(), $request->input(Fortify::username()))->first();

        if (! $user || ! Hash::check($request->password, $user->password)) {
            return null;
        }

        if (! $user->is_active) {
            throw ValidationException::withMessages([
                Fortify::username() => 'Akun Anda tidak aktif. Silakan hubungi administrator.',
            ]);
        }

        return $user;
    }
}
