from typing import Optional, Union
from urllib.parse import urljoin

from ..._request_handler import AsyncRequestHandler, RequestHandler


class BaseStore:
    def __init__(self, request_handler: Union[RequestHandler, AsyncRequestHandler]):
        self._request_handler = request_handler

    def _pre_get_files_and_folders(
        self,
        store_connector_id: str,
        project_id: str,
        folder_id: Optional[str] = None,
        page_number: Optional[int] = None,
        page_size: Optional[int] = None,
        sort_by: Optional[str] = None,
        sort_order: Optional[str] = None,
        filter_by: Optional[str] = None,
        filter_value: Optional[str] = None,
        correlation_id: Optional[str] = None,
    ):
        """
        Prepare request data for get files and folders endpoint.

        This internal method constructs the URL and query parameters for
        retrieving files and folders from a store connector.

        Args:
            store_connector_id: ID of the store connector
            project_id: ID of the project
            folder_id: Optional folder ID to browse within a specific folder
            page_number: Page number for pagination
            page_size: Number of items per page
            sort_by: Field to sort by
            sort_order: Sort order (ASC or DESC)
            filter_by: Field to filter by
            filter_value: Value to filter by
            correlation_id: Optional correlation ID for tracing

        Returns:
            RequestData: Prepared request data for the get files and folders endpoint
        """
        # Build URL with optional folder_id
        if folder_id:
            url_path = f"datastore/v1/store/{store_connector_id}/folders/{folder_id}"
        else:
            url_path = f"datastore/v1/store/{store_connector_id}/folders/"

        url = urljoin(self._request_handler.base_url, url_path)

        # Build query parameters
        params = {"projectId": project_id}

        if page_number is not None:
            params["pagingParameters.pageNumber"] = page_number
        if page_size is not None:
            params["pagingParameters.pageSize"] = page_size
        if sort_by is not None:
            params["sortingParameters.sortBy"] = sort_by
        if sort_order is not None:
            params["sortingParameters.sortOrder"] = sort_order
        if filter_by is not None:
            params["filteringParameters.filterBy"] = filter_by
        if filter_value is not None:
            params["filteringParameters.filterValue"] = filter_value

        request_data = self._request_handler.prepare_request(
            url, params=params, payload=None, correlation_id=correlation_id
        )

        return request_data
