<?php declare(strict_types=1);

namespace App\Services;

use App\Dto\Request\Authorization;
use App\Repositories\UserRepository;
use App\ServiceResults\ServiceResultError;
use App\ServiceResults\ServiceResultSuccess;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

final class AuthService extends Service
{
    public function __construct(
        private readonly UserRepository $userRepository
    ) { }

    public function authorization(Authorization $authorization): ServiceResultError | ServiceResultSuccess
    {
        $user = $this->userRepository->getUserByEmail($authorization->getEmail());
        if (is_null($user)) {
            return $this->errUnauthorized(__('auth.failed'));
        }
        if (Hash::check($authorization->getPassword(), $user->password) !== true) {
            return $this->errUnauthorized(__('auth.password'));
        }
        if ($user->is_active === false) {
            return $this->errFobidden(__('auth.disabled'));
        }

        try {
            Auth::login($user, $authorization->getRemember());
        } catch (\Throwable $e) {
            report($e);
            return $this->errService(__('Server Error'));
        }

        return $this->ok(__('auth.success'));
    }
}
