from typing import Optional
from uuid import UUID

from app.core.module_framework.cqrs import ICommand, ICommandHandler
from app.core.module_framework.decorators import transactional, log_execution
from app.core.postgres.base_pkg.base_client import BasePostgresClient
from app.modules.auth.domain.entities import User
from app.modules.auth.infrastructure.repositories import UserRepository
import hashlib # For dummy hashing

class RegisterUserCommand(ICommand):
    username: str
    email: str
    password: str
    role: str = "USER"

class RegisterUserCommandHandler(ICommandHandler[RegisterUserCommand, UUID]):
    def __init__(self, postgres_client: BasePostgresClient):
        self._postgres_client = postgres_client

    @log_execution
    @transactional
    def handle(self, command: RegisterUserCommand) -> UUID:
        repo = UserRepository(self._conn)
        
        # Kiểm tra user tồn tại (nếu cần)
        if repo.get_by_username(command.username):
            raise ValueError("Username đã tồn tại")
            
        hashed_pw = hashlib.sha256(command.password.encode()).hexdigest()
        
        user = User(
            username=command.username,
            email=command.email,
            hashed_password=hashed_pw,
            role=command.role
        )
        
        repo.save(user)
        return user.id
