from flask import jsonify, request, current_app
from pydantic import ValidationError
from app.models.login.login_response import UserResponseModel
from app.schemas.basic_response_schema import ResponseSchema
from app.schemas.google_login_schema import GoogleLoginSchema
from app.schemas import LoginSchema
from app.services import UserService, AuthService
from app.exception import AuthException
from app.mapper import UserMapper
from app.helpers import make_response
import logging

logging = logging.getLogger(__name__)


class AuthController:
    def __init__(self, userService: UserService, authService: AuthService):
        self.user_service = userService
        self.auth_service = authService

    def login(self):
        try:
            data = request.get_json()
            dataSchema = LoginSchema(**data)
            response = self.auth_service.login(dataSchema)

            if response is None:
                return make_response(message="User is not registered", status_code=401)
            return (
                jsonify(
                    ResponseSchema(
                        message="Register success",
                        data=UserMapper.user_entity_to_response(response),
                    ).model_dump()
                ),
                200,
            )
        except ValidationError as e:
            current_app.logger.error(f"Validation error: {e}")
            response = ResponseSchema(message="Invalid input", data=None, meta=None)
            return jsonify(response.model_dump()), 400

        except Exception as e:
            current_app.logger.error(
                f"Error during Google login: {str(e)}", exc_info=True
            )
            response = ResponseSchema(
                message="Internal server error", data=None, meta=None
            )
            return jsonify(response.model_dump()), 500

    def google_login(self):
        """Handles Google Login via ID Token verification"""
        try:
            data = request.get_json()

            # Validasi data dengan Pydantic
            validated_data = GoogleLoginSchema(**data)
            id_token = validated_data.token_id

            # Verifikasi ID Token ke layanan AuthService
            user_info = self.auth_service.verify_google_id_token(id_token)
            if not user_info:
                current_app.logger.error("Invalid Google ID Token")
                response = ResponseSchema(
                    message="Invalid Google ID Token", data=None, meta=None
                )
                return jsonify(response.model_dump()), 401

            response = ResponseSchema(
                message="Login successful",
                data=UserMapper.user_entity_to_response(user_info),
                meta=None,
            )
            return jsonify(response.model_dump()), 200

        except ValidationError as e:
            current_app.logger.error(f"Validation error: {e}")
            response = ResponseSchema(message="Invalid input", data=None, meta=None)
            return jsonify(response.model_dump()), 400

        except AuthException as e:
            current_app.logger.error(f"Auth error: {e}")
            response = ResponseSchema(message=e, data=None, meta=None)
            return jsonify(response.model_dump()), 400

        except Exception as e:
            current_app.logger.error(
                f"Error during Google login: {str(e)}", exc_info=True
            )
            response = ResponseSchema(
                message="Internal server error", data=None, meta=None
            )
            return jsonify(response.model_dump()), 500

    def logout(self):
        return jsonify({"message": "logout"}), 200
