from sqlalchemy.orm import Session
from app.crud.user import get_user_by_username, get_territory, update_password
from app.utils.jwt import create_access_token

class AuthService:
    @staticmethod
    def login_user(db: Session, username: str, password: str) -> dict:
        user = get_user_by_username(db, username)
        if not user or not user.verify_password(password):
            raise ValueError("Invalid username or password")

        if user.is_active == 0:
            raise ValueError("User is not active")
        
        role_map = {
            1: "Circle",
            2: "Region",
            3: "Area",
            4: "Branch",
            5: "DSE",
            10: "DSE_BOTH",
            11: "TL_FTTH",
            12: "AE_FTTH",
        }

        role = role_map.get(int(user.role), None)
        allowed_roles = {5, 10, 11, 12}

        if int(user.role) not in allowed_roles:
            raise ValueError("User does not have access to this application")

        territory = get_territory(db, user.territory_id)
        access_token = create_access_token(data={"sub": user.username})

        return {
            "data": {
                "id": user.id,
                "username": user.username,
                "role": role,
                "territory": territory.name,
                "brand": user.brand,
            },
            "token": {
                "access_token": access_token,
                "token_type": "bearer"
            }
        }

    @staticmethod
    def refresh_token_for_user(db: Session, username: str) -> str:
        user = get_user_by_username(db, username)
        if not user:
            raise ValueError("Invalid username or password")
        
        return create_access_token(data={"sub": user.username})

    @staticmethod
    def change_user_password(db: Session, username: str, current_password: str, new_password: str):
        user = get_user_by_username(db, username)
        if not user or not user.verify_password(current_password):
            raise ValueError("Invalid username or password")
        
        update_password(db, user, new_password)
