from typing import Optional from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from src.config import settings from src.models.seller_profile import SellerProfile from src.models.user import User, UserRole from src.schemas.auth import AuthResponse, LoginRequest, RegisterRequest, UserResponse from src.utils.exceptions import ConflictError, UnauthorizedError from src.utils.security import create_access_token, hash_password, verify_password async def register_user(db: AsyncSession, payload: RegisterRequest) -> AuthResponse: """ Register a new user account. Checks email and username uniqueness, hashes the password, creates the User row, and — if the role is seller — auto-creates a SellerProfile in the same transaction. Returns an AuthResponse with a fresh JWT so the client can log in immediately after registration. """ # Uniqueness checks existing_email = await db.execute(select(User).where(User.email == payload.email)) if existing_email.scalar_one_or_none(): raise ConflictError("Email is already registered") existing_username = await db.execute( select(User).where(User.username == payload.username) ) if existing_username.scalar_one_or_none(): raise ConflictError("Username is already taken") # Create user user = User( email=payload.email, username=payload.username, full_name=payload.full_name, hashed_password=hash_password(payload.password), role=payload.role, ) db.add(user) # flush to get user.id without committing the transaction await db.flush() # Auto-create SellerProfile for seller registrations if payload.role == UserRole.SELLER: seller_profile = SellerProfile(user_id=user.id) db.add(seller_profile) return _build_auth_response(user) async def login_user(db: AsyncSession, payload: LoginRequest) -> AuthResponse: """ Authenticate a user with email + password. Uses the same error message for wrong email and wrong password to avoid leaking which field is incorrect. """ result = await db.execute(select(User).where(User.email == payload.email)) user = result.scalar_one_or_none() if not user or not verify_password(payload.password, user.hashed_password): raise UnauthorizedError("Incorrect email or password") if not user.is_active: raise UnauthorizedError("Account is deactivated. Please contact support.") return _build_auth_response(user) async def get_user_by_id(db: AsyncSession, user_id: str) -> Optional[User]: """Fetch a user by their UUID string. Returns None if not found.""" result = await db.execute(select(User).where(User.id == user_id)) return result.scalar_one_or_none() def _build_auth_response(user: User) -> AuthResponse: """Mint a fresh JWT and assemble the AuthResponse. Called by register and login.""" token = create_access_token( subject=user.id, extra_claims={"role": user.role.value}, ) return AuthResponse( user=UserResponse.model_validate(user), access_token=token, token_type="bearer", expires_in=settings.jwt_expiry_hours * 3600, )