<?php

declare(strict_types=1);

namespace App\Auth;

use App\Models\User;
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Support\Facades\Hash;

class LaraBlogUserProvider extends EloquentUserProvider
{
    public function retrieveByCredentials(array $credentials): ?Authenticatable
    {
        if ($credentials === []) {
            return null;
        }

        $query = $this->newModelQuery();

        foreach ($credentials as $key => $value) {
            if (in_array($key, ['password', 'token'], true)) {
                continue;
            }

            if ($key === 'login') {
                $query->where(function ($builder) use ($value): void {
                    $builder->where('email', $value)
                        ->orWhere('username', $value);
                });

                continue;
            }

            $query->where($key, $value);
        }

        return $query->first();
    }

    public function validateCredentials(Authenticatable $user, array $credentials): bool
    {
        $plain = (string) ($credentials['password'] ?? '');

        if ($plain === '') {
            return false;
        }

        if ($this->hasValidBcryptPassword($user, $plain)) {
            return true;
        }

        if ($user instanceof User) {
            return $user->attemptLegacyPasswordUpgrade($plain);
        }

        return false;
    }

    protected function hasValidBcryptPassword(Authenticatable $user, string $plain): bool
    {
        $hashed = $user->getAuthPassword();

        if (! is_string($hashed) || $hashed === '') {
            return false;
        }

        return Hash::check($plain, $hashed);
    }
}
