<?php

declare(strict_types=1);

namespace App\Auth;

use Illuminate\Auth\EloquentUserProvider;

/**
 * 后台登录：优先按 login_account 匹配，再按 email 精确匹配（忽略空邮箱）。
 */
final class DberpEloquentUserProvider extends EloquentUserProvider
{
    /**
     * @param  array<string, mixed>  $credentials
     */
    public function retrieveByCredentials(#[\SensitiveParameter] array $credentials)
    {
        if (! isset($credentials['dberp_login_identifier'])) {
            return parent::retrieveByCredentials($credentials);
        }

        $login = trim((string) $credentials['dberp_login_identifier']);

        if ($login === '') {
            return null;
        }

        $model = $this->createModel();

        $byLoginAccount = $model->newQuery()
            ->where('login_account', $login)
            ->first();

        if ($byLoginAccount !== null) {
            return $byLoginAccount;
        }

        return $model->newQuery()
            ->whereNotNull('email')
            ->where('email', $login)
            ->first();
    }
}
