<?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\Log;
use Throwable;

// Сервіс для роботи з користувачами
final class UserService
{
    public function __construct(
        private readonly UserRepositoryInterface $repository
    ) {
    }

    public function create(string $username, string $passwordHash): ?User
    {
        try {
            $user = $this->repository->create([
                'username' => $username,
                'password_hash' => $passwordHash,
                'session_token' => null,
                'last_activity' => null,
                'is_active' => true,
            ]);

            Log::Info('UserService::create: User created', ['username' => $username]);
            return $user;
        } catch (Throwable $e) {
            Log::Error('UserService::create error: ' . $e->getMessage());
            return null;
        }
    }

    public function update(User $user): bool
    {
        try {
            $result = $this->repository->update($user->id, [
                'username' => $user->username,
                'password_hash' => $user->passwordHash,
                'session_token' => $user->sessionToken,
                'last_activity' => $user->lastActivity,
                'is_active' => $user->isActive,
            ]);
            if ($result) {
                Log::Info('UserService::update: User updated', ['user_id' => $user->id]);
            }
            return $result;
        } catch (Throwable $e) {
            Log::Error('UserService::update error: ' . $e->getMessage());
            return false;
        }
    }

    public function delete(int $userId): bool
    {
        try {
            $result = $this->repository->delete($userId);
            if ($result) {
                Log::Info('UserService::delete: User deleted', ['user_id' => $userId]);
            }
            return $result;
        } catch (Throwable $e) {
            Log::Error('UserService::delete error: ' . $e->getMessage());
            return false;
        }
    }

    public function findById(int $userId): ?User
    {
        return $this->repository->findById($userId);
    }

    public function findByUsername(string $username): ?User
    {
        $users = $this->repository->findAll(['username' => $username]);
        return $users[0] ?? null;
    }
}
