<?php

declare(strict_types=1);

namespace Flowaxy\Domain\User\Services;

use Flowaxy\Contracts\Domain\User\UserRepositoryInterface;
use Flowaxy\Domain\User\Entities\User;
use Flowaxy\Support\Facades\Hash;
use Flowaxy\Support\Facades\Log;
use Throwable;

// Сервіс аутентифікації
final class AuthenticationService
{
    public function __construct(
        private readonly UserRepositoryInterface $repository
    ) {
    }

    public function authenticate(string $username, string $password): ?User
    {
        $users = $this->repository->findAll(['username' => $username]);
        $user = $users[0] ?? null;

        if ($user === null) {
            try {
                Log::Warning('AuthenticationService::authenticate: User not found', ['username' => $username]);
            } catch (Throwable $e) {
                // Ignore logging errors
            }
            return null;
        }

        if (!Hash::check($password, $user->passwordHash)) {
            try {
                Log::Warning('AuthenticationService::authenticate: Invalid password', ['username' => $username]);
            } catch (Throwable $e) {
                // Ignore logging errors
            }
            return null;
        }

        if (!$user->isActive) {
            try {
                Log::Warning('AuthenticationService::authenticate: User is inactive', ['user_id' => $user->id]);
            } catch (Throwable $e) {
                // Ignore logging errors
            }
            return null;
        }

        try {
            Log::Info('AuthenticationService::authenticate: User authenticated', ['user_id' => $user->id]);
        } catch (Throwable $e) {
            // Ignore logging errors
        }
        return $user;
    }

    public function check(?string $sessionToken): ?User
    {
        if ($sessionToken === null || $sessionToken === '') {
            return null;
        }

        return null;
    }
}
