from flask import jsonify, current_app
from typing import Optional, Union
from app.schemas import ResponseSchema, MetaSchema
import math


def calculate_total_page(total_data: int, page_size: int) -> int:
    if not page_size or page_size <= 0:
        return 1
    return math.ceil(total_data / page_size)


def make_response(
    message: str,
    data: Optional[Union[dict, list]] = None,
    page: Optional[int] = None,
    page_size: Optional[int] = None,
    total_all_data: Optional[int] = None,
    status_code: int = 200,
):
    meta = None
    if page is not None and page_size is not None and total_all_data is not None:
        meta = MetaSchema(
            current_page=page,
            total_all_data=total_all_data,
            total_data=len(data) if data else 0,
            total_page=calculate_total_page(total_all_data, page_size),
        )

    response = ResponseSchema(
        message=message,
        data=data,
        meta=meta,
    )
    return jsonify(response.model_dump()), status_code


def make_error_response(
    err: Union[Exception, str],
    log_message: Optional[str] = None,
    status_code: int = 500,
):
    """Logs the error and returns a standardized error response"""
    error_message = str(err) if isinstance(err, Exception) else err
    log_msg = log_message or f"An error occurred: {error_message}"
    current_app.logger.error(log_msg, exc_info=True)

    response = ResponseSchema(message="Internal server error", data=None, meta=None)
    return jsonify(response.model_dump()), status_code
