<?php

namespace App\Domain\Services;

use App\Config\RolesConfig;
use App\Domain\Entities\User;
use App\Domain\Repositories\UserRepositoryInterface;
use App\Exceptions\AuthException;
use App\Infrastructure\Security\PasswordHasher;
use App\Support\Str;

class AuthService
{
    public function __construct(
        private UserRepositoryInterface $users,
        private PasswordHasher $hasher,
        private TokenService $tokens
    ) {
    }

    public function register(array $data): array
    {
        $email = strtolower(trim($data['email']));
        $username = trim($data['username'] ?? Str::slug($data['name']));

        if ($this->users->findByEmail($email)) {
            throw new AuthException('Email already registered', 409, ['field' => 'email']);
        }

        if ($this->users->findByUsername($username)) {
            $username .= '-' . substr(Str::random(8), 0, 8);
        }

        $user = $this->users->create(new User(
            null,
            trim($data['name']),
            $username,
            $email,
            $this->hasher->hash($data['password']),
            trim($data['phone'] ?? ''),
            trim($data['address'] ?? ''),
            (int)($data['role_id'] ?? RolesConfig::defaultRoleId()),
            (int)($data['status_id'] ?? 142345678901234591)
        ));

        return ['user' => $user->publicArray()];
    }

    public function login(string $email, string $password): array
    {
        $user = $this->users->findByEmail(strtolower(trim($email)));
        if (!$user || !$this->hasher->verify($password, $user->password)) {
            throw new AuthException('Invalid email or password', 401);
        }

        return [
            'user' => $user->publicArray(),
            'tokens' => $this->tokens->issuePair((int)$user->id, $user->roleId),
        ];
    }
}
