from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.user import User
from app.core.security import verify_password, create_access_token, create_refresh_token, hash_password
from app.core.exceptions import bad_request

class AuthService:
    @staticmethod
    async def login(db: AsyncSession, email: str, password: str):
        user = await db.scalar(select(User).where(User.email == email, User.status == "active"))
        if not user or not verify_password(password, user.password_hash):
            raise bad_request("Invalid email or password")
        return user, create_access_token(user.id, user.brand_id, user.role_id), create_refresh_token(user.id, user.brand_id, user.role_id)

    @staticmethod
    async def change_password(db, user, current, new):
        if not verify_password(current, user.password_hash):
            raise bad_request("Current password is incorrect")
        user.password_hash = hash_password(new)
        await db.commit()
