# Copyright (c) CloudZero - ALL RIGHTS RESERVED - PROPRIETARY AND CONFIDENTIAL
# Unauthorized copying of this file and/or project, via any medium is strictly prohibited.
# Direct all questions to legal@cloudzero.com

import re

from aws_lambda_powertools.event_handler.api_gateway import CORSConfig

CLOUDZERO_DOMAINS = r'^https://.*\.cloudzero\.com$'


class WebCORSConfig(CORSConfig):
    """
    CloudZero Web CORS configuration for API Gateway responses.

    Extends AWS PowerTools CORSConfig with CloudZero-specific default values
    for allowed origins and other CORS settings suitable for CloudZero web applications.
    """

    def __init__(
        self,
        extra_origins: list[str] | None = None,
        allow_headers: list[str] | None = None,
        expose_headers: list[str] | None = None,
        max_age: int | None = None,
        allow_credentials: bool = False,
    ):
        """
        Initialize CloudZero Web CORS configuration.

        Args:
            extra_origins: Additional allowed origins. Defaults to ['demo.cloudzero.com'].
            allow_headers: List of allowed request headers.
            expose_headers: List of headers to expose to the client.
            max_age: Maximum age for preflight cache in seconds.
            allow_credentials: Whether to allow credentials in CORS requests.
            max_age: Maximum age for preflight cache in seconds.
            allow_credentials: Whether to allow credentials in CORS requests.
        """

        super().__init__(
            allow_origin='https://app.cloudzero.com',
            extra_origins=['https://demo.cloudzero.com', *(extra_origins or [])],
            allow_headers=allow_headers,
            expose_headers=expose_headers,
            max_age=max_age,
            allow_credentials=allow_credentials,
        )

    def _check_and_update_cloudzero_domain(self, extracted_origin: str | None) -> None:
        if (extracted_origin and extracted_origin not in self._allowed_origins) and re.match(
            CLOUDZERO_DOMAINS, str(extracted_origin)
        ):
            self._allowed_origins.append(extracted_origin)

    def to_dict(self, origin: str | None) -> dict[str, str]:
        self._check_and_update_cloudzero_domain(origin)
        return super().to_dict(origin)

    def allowed_origin(self, extracted_origin: str) -> str | None:
        self._check_and_update_cloudzero_domain(extracted_origin)
        return super().allowed_origin(extracted_origin)
