"""Create user use case."""

from dataclasses import dataclass
from datetime import datetime

from vexen_user.application.dto import (
	BaseResponse,
	CreateUserRequest,
	UserResponse,
)
from vexen_user.domain.entity import User
from vexen_user.domain.repository import IUserRepositoryPort


@dataclass
class CreateUser:
	"""Create a new user"""

	repository: IUserRepositoryPort

	async def __call__(self, data: CreateUserRequest) -> BaseResponse[UserResponse]:
		try:
			# Check if email already exists
			existing = await self.repository.get_by_email(data.email)
			if existing:
				return BaseResponse.fail(f"User with email {data.email} already exists")

			# TODO: Hash password using auth service
			# For now, we store it as-is (this should be handled by vexen-auth)

			# Create user entity
			user = User(
				id=None,  # Will be generated by DB
				email=data.email,
				name=data.name,
				avatar=data.avatar,
				status="active",
				created_at=datetime.now(),
				user_metadata=data.user_metadata or {},
			)

			# Save user
			saved_user = await self.repository.save(user)

			response = UserResponse(
				id=saved_user.id,
				email=saved_user.email,
				name=saved_user.name,
				avatar=saved_user.avatar,
				status=saved_user.status,
				created_at=saved_user.created_at,
				last_login=saved_user.last_login,
			)

			return BaseResponse.ok(response)

		except Exception as e:
			return BaseResponse.fail(f"Error creating user: {str(e)}")
