# coding: utf-8

"""
    CATAPA API

    # Introduction CATAPA API uses RESTful API style. It uses JSON data format for data exchange and utilizes HTTP verbs as appropriate.  For authorization & authentication, CATAPA API uses OAuth 2.0 protocol.  # Base URL Production: https://api.catapa.com  # Authentication Clients need to acquire an access token before they send HTTP requests to resource endpoints.  <SecurityDefinitions />  ## Validate Access Token    Use this endpoint to verify if an access token is valid and was issued by the API gateway. The endpoint supports both user tokens and client credentials tokens.    | **HTTP Method**  | `GET`                                                |                                         |   |------------------|------------------------------------------------------|-----------------------------------------|   | **URL**          | `<base-url>/v1/oauth-clients/validate-access-token`  |                                         |   | **Headers**      | `Authorization`                                      | `Bearer <access-token>`                 |   |                  | `Tenant`                                             | Your tenant identifier (e.g., \"catapa\") |  ### Example request using `curl`    ```bash   curl --location '<base-url>/v1/oauth-clients/validate-access-token' \\     --header 'Tenant: catapa' \\     --header 'Authorization: Bearer <access-token>'   ```  ### Response codes  - **200 OK**: Token is valid - **401 Unauthorized**: Token is invalid or expired  ### Notes  - This endpoint validates both user authentication tokens and client credentials tokens - For server-to-server communication, use client credentials flow with the token in the Authorization header - No response body is returned; the status code indicates the validation result - The `Tenant` header is required to specify which tenant context to validate the token against  # HTTP Headers Each request should contain the following headers.  |Headers        |Description  | |---------------|-------------| |Tenant         |Tenant name. e.g. Catapa| |Authorization  |For authentication. Value format: Bearer <access-token>|  Example HTTP Request using cURL: ```bash curl <base-url>/core/v1/employees?page=0&size=10 \\ -H \"Tenant: <tenant name>\" \\ -H \"Authorization: Bearer <access-token>\" ```  # Rate Limit To ensure optimal API performance and fair usage for all users, we implement rate limiting. The general limit is **400 requests per minute, per Client ID**. If you exceed the rate limit, you will receive an HTTP 429 (Too Many Requests) error response.  # Pagination The API provides `page` & `size` query params. `page` is a page number starting from 0. `size` is number of elements per page. Maximum value of `size` is 50.  Every paginated endpoints will have following response format: ``` {   \"content\": [     { ... },     { ... }   ],   \"number\": 0, // page number   \"size\": 10, // page size   \"numberOfElements\": 10, // number of element in this current page   \"totalElements\": 100,   \"totalPages\": 10 } ```  # Search Query You can perform search operations in some endpoints by setting the query parameter. Query value parameter constructed with following format:  ```bash ?query=<key><operator><value>,<key><operator><value> ```  Explanations: | Format | Descriptions | |-|-| | `<key>` | Key name to search certain fields | | `<operator>`   | Operation to apply on certain fields.<br>Supported operators: `:` `<` `>` | | `<value>` | Value to apply on search. **Value should be encoded using URL encoder**. For examples:<br><br>Plain: `John Doe`<br>Encoded: `John%20Doe` | | `,` | AND operator |   For example, the `/core/v1/employees` endpoint has following search query. |Key                    |Supported Operators  |Notes  | |-----------------------|---------------------|-------| |identificationNumberIn | `:`                 |Equal operator with multiple values. Each value should separated with delimiters `;`| |name                   | `:`                 |Like operator| |startDate              | `:`<br/>`>`<br/>`<` |Equal<br>Greater than or equal to<br>Less than or equal to|  Clients can construct search query with these following variations:  1. Search an employee with ID number 1111 ```bash curl <base-url>/core/v1/employees?query=identificationNumberIn:1111 ``` 1. Search multiple employees with ID number 1111 and 2222 ```bash curl <base-url>/core/v1/employees?query=identificationNumberIn:1111;2222 ``` 1. Search employees with name `John Doe` ```bash curl <base-url>/core/v1/employees?query=name:John%20Doe ``` 1. Search all employees with start date between 2020-01-01 and 2020-12-31: ```bash curl <base-url>/core/v1/employees?query=startDate>2020-01-01,startDate<2020-12-31 ``` 

    The version of the OpenAPI document: 1.0.0
    Contact: support@catapa.com
    Generated by OpenAPI Generator (https://openapi-generator.tech)

    Do not edit the class manually.
"""  # noqa: E501

from typing import Any, Optional
from typing_extensions import Self

class OpenApiException(Exception):
    """The base exception class for all OpenAPIExceptions"""


class ApiTypeError(OpenApiException, TypeError):
    def __init__(self, msg, path_to_item=None, valid_classes=None,
                 key_type=None) -> None:
        """ Raises an exception for TypeErrors

        Args:
            msg (str): the exception message

        Keyword Args:
            path_to_item (list): a list of keys an indices to get to the
                                 current_item
                                 None if unset
            valid_classes (tuple): the primitive classes that current item
                                   should be an instance of
                                   None if unset
            key_type (bool): False if our value is a value in a dict
                             True if it is a key in a dict
                             False if our item is an item in a list
                             None if unset
        """
        self.path_to_item = path_to_item
        self.valid_classes = valid_classes
        self.key_type = key_type
        full_msg = msg
        if path_to_item:
            full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
        super(ApiTypeError, self).__init__(full_msg)


class ApiValueError(OpenApiException, ValueError):
    def __init__(self, msg, path_to_item=None) -> None:
        """
        Args:
            msg (str): the exception message

        Keyword Args:
            path_to_item (list) the path to the exception in the
                received_data dict. None if unset
        """

        self.path_to_item = path_to_item
        full_msg = msg
        if path_to_item:
            full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
        super(ApiValueError, self).__init__(full_msg)


class ApiAttributeError(OpenApiException, AttributeError):
    def __init__(self, msg, path_to_item=None) -> None:
        """
        Raised when an attribute reference or assignment fails.

        Args:
            msg (str): the exception message

        Keyword Args:
            path_to_item (None/list) the path to the exception in the
                received_data dict
        """
        self.path_to_item = path_to_item
        full_msg = msg
        if path_to_item:
            full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
        super(ApiAttributeError, self).__init__(full_msg)


class ApiKeyError(OpenApiException, KeyError):
    def __init__(self, msg, path_to_item=None) -> None:
        """
        Args:
            msg (str): the exception message

        Keyword Args:
            path_to_item (None/list) the path to the exception in the
                received_data dict
        """
        self.path_to_item = path_to_item
        full_msg = msg
        if path_to_item:
            full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
        super(ApiKeyError, self).__init__(full_msg)


class ApiException(OpenApiException):

    def __init__(
        self, 
        status=None, 
        reason=None, 
        http_resp=None,
        *,
        body: Optional[str] = None,
        data: Optional[Any] = None,
    ) -> None:
        self.status = status
        self.reason = reason
        self.body = body
        self.data = data
        self.headers = None

        if http_resp:
            if self.status is None:
                self.status = http_resp.status
            if self.reason is None:
                self.reason = http_resp.reason
            if self.body is None:
                try:
                    self.body = http_resp.data.decode('utf-8')
                except Exception:
                    pass
            self.headers = http_resp.headers

    @classmethod
    def from_response(
        cls, 
        *, 
        http_resp, 
        body: Optional[str], 
        data: Optional[Any],
    ) -> Self:
        if http_resp.status == 400:
            raise BadRequestException(http_resp=http_resp, body=body, data=data)

        if http_resp.status == 401:
            raise UnauthorizedException(http_resp=http_resp, body=body, data=data)

        if http_resp.status == 403:
            raise ForbiddenException(http_resp=http_resp, body=body, data=data)

        if http_resp.status == 404:
            raise NotFoundException(http_resp=http_resp, body=body, data=data)

        # Added new conditions for 409 and 422
        if http_resp.status == 409:
            raise ConflictException(http_resp=http_resp, body=body, data=data)

        if http_resp.status == 422:
            raise UnprocessableEntityException(http_resp=http_resp, body=body, data=data)

        if 500 <= http_resp.status <= 599:
            raise ServiceException(http_resp=http_resp, body=body, data=data)
        raise ApiException(http_resp=http_resp, body=body, data=data)

    def __str__(self):
        """Custom error messages for exception"""
        error_message = "({0})\n"\
                        "Reason: {1}\n".format(self.status, self.reason)
        if self.headers:
            error_message += "HTTP response headers: {0}\n".format(
                self.headers)

        if self.body:
            error_message += "HTTP response body: {0}\n".format(self.body)

        if self.data:
            error_message += "HTTP response data: {0}\n".format(self.data)

        return error_message


class BadRequestException(ApiException):
    pass


class NotFoundException(ApiException):
    pass


class UnauthorizedException(ApiException):
    pass


class ForbiddenException(ApiException):
    pass


class ServiceException(ApiException):
    pass


class ConflictException(ApiException):
    """Exception for HTTP 409 Conflict."""
    pass


class UnprocessableEntityException(ApiException):
    """Exception for HTTP 422 Unprocessable Entity."""
    pass


def render_path(path_to_item):
    """Returns a string representation of a path"""
    result = ""
    for pth in path_to_item:
        if isinstance(pth, int):
            result += "[{0}]".format(pth)
        else:
            result += "['{0}']".format(pth)
    return result
