import hashlib

from app.modules.user.user_model import UserModel
from app.modules.user.user_repository import UserRepository


class UserService:

    def __init__(self):

        self.repo = UserRepository()

    # PASSWORD HASH
    def hash_password(
        self,
        password: str
    ) -> str:

        return hashlib.sha256(
            password.encode()
        ).hexdigest()

    # GET USER BY EMAIL
    async def get_user_by_email(
        self,
        email: str
    ):

        return await self.repo.find_by_email(
            email
        )

    # REGISTER WITH EMAIL
    async def register_with_email(
        self,
        email: str,
        password: str
    ):

        existing_user = await self.repo.find_by_email(
            email
        )

        if existing_user:

            return {
                "success": False,
                "message": "Email already registered"
            }

        hashed_password = self.hash_password(
            password
        )

        user = UserModel(
            email=email,
            password=hashed_password
        )

        created_user = await self.repo.create_user(
            user
        )

        return {
            "success": True,
            "user": created_user
        }

    # LOGIN WITH EMAIL + PASSWORD
    async def login_with_email(
        self,
        email: str,
        password: str
    ):

        user = await self.repo.find_by_email(
            email
        )

        # EMAIL NOT FOUND
        if not user:

            return {
                "success": False,
                "message": "User not found"
            }

        # ACCOUNT HAS NO PASSWORD
        # Example: Google-only account
        if not user.get("password"):

            return {
                "success": False,
                "message": "This account does not have a password login"
            }

        # PASSWORD CHECK
        hashed_password = self.hash_password(
            password
        )

        if user["password"] != hashed_password:

            return {
                "success": False,
                "message": "Invalid password"
            }

        # ACTIVE CHECK
        if not user.get("is_active", True):

            return {
                "success": False,
                "message": "User account is inactive"
            }

        return {
            "success": True,
            "user": user
        }

    # LOGIN WITH GOOGLE
    async def login_with_google(
        self,
        google_id: str,
        email: str,
        name: str | None = None,
        profile_image: str | None = None
    ):

        # FIND BY GOOGLE ID
        user = await self.repo.find_by_google_id(
            google_id
        )

        if user:

            if not user.get("is_active", True):

                return {
                    "success": False,
                    "message": "User account is inactive"
                }

            update_data = {}

            if name:
                update_data["name"] = name

            if profile_image:
                update_data["profile_image"] = profile_image

            if update_data:

                user = await self.repo.update_user(
                    str(user["_id"]),
                    update_data
                )

            return {
                "success": True,
                "user": user
            }

        # FIND BY EMAIL
        existing_user = await self.repo.find_by_email(
            email
        )

        if existing_user:

            if not existing_user.get("is_active", True):

                return {
                    "success": False,
                    "message": "User account is inactive"
                }

            updated_user = await self.repo.update_user(
                str(existing_user["_id"]),
                {
                    "google_id": google_id,
                    "name": name,
                    "profile_image": profile_image
                }
            )

            return {
                "success": True,
                "user": updated_user
            }

        # CREATE NEW GOOGLE USER
        user = UserModel(
            email=email,
            google_id=google_id,
            name=name,
            profile_image=profile_image
        )

        created_user = await self.repo.create_user(
            user
        )

        return {
            "success": True,
            "user": created_user
        }

    # FORGOT PASSWORD
    async def forgot_password(
        self,
        email: str
    ):

        user = await self.repo.find_by_email(
            email
        )

        if not user:

            return {
                "success": False,
                "message": "User not found"
            }

        if not user.get("is_active", True):

            return {
                "success": False,
                "message": "User account is inactive"
            }

        # Temporary hardcoded OTP
        return {
            "success": True,
            "message": "OTP sent successfully",
            "otp": "1234"
        }


    # RESET PASSWORD
    async def reset_password(
        self,
        email: str,
        otp_code: str,
        new_password: str
    ):

        user = await self.repo.find_by_email(
            email
        )

        if not user:

            return {
                "success": False,
                "message": "User not found"
            }

        if not user.get("is_active", True):

            return {
                "success": False,
                "message": "User account is inactive"
            }

        # Temporary hardcoded OTP
        if otp_code != "1234":

            return {
                "success": False,
                "message": "Invalid OTP"
            }

        hashed_password = self.hash_password(
            new_password
        )

        updated_user = await self.repo.update_user(
            str(user["_id"]),
            {
                "password": hashed_password
            }
        )

        if not updated_user:

            return {
                "success": False,
                "message": "Failed to update password"
            }

        return {
            "success": True,
            "message": "Password updated successfully"
        }
 
 
    async def soft_delete_account(
        self,
        user_id: str
    ):

        user = await self.repo.find_by_id(
            user_id
        )

        if not user:

            return {
                "success": False,
                "message": "User not found"
            }
            
        if not user.get("is_active", True):

            return {
                "success": False,
                "message": "User account is already inactive"
            }
        
        deleted_user = await self.repo.soft_delete_user(
            user_id
        )
        
        if not deleted_user:
            
            return {
                "success": False,
                "message": "Failed to soft delete user"
            }
        return {
            "success": True,
            "message": "User account has been deactivated"
        }
        

user_service = UserService()