from typing import TypedDict, Literal, List

from flask import request, jsonify, make_response, session

from src.config import Configuration
from src.lib.dms import (
    has_unapproved_dms,
    get_all_dms,
    get_all_dms_by_query,
    get_all_dms_by_query_count,
    get_all_dms_count,
)
from src.lib.api import create_client_error_response
from src.utils.utils import get_query_parameters_dict, parse_int, positive_or_none, step_int
from src.types.kemono import Approved_DM

from src.pages.api.v1 import v1api_bp


class TDDMsProps(TypedDict):
    currentPage: Literal["artists"]
    count: int
    limit: int
    dms: List[Approved_DM]


@v1api_bp.get("/dms")
def get_api_dms():
    base = get_query_parameters_dict(request, on_errors="ignore", clean_query_string=True)

    limit = 50
    max_offset = limit * 1000  # only load 1000 pages of any result
    offset = positive_or_none(step_int(parse_int(base.pop("o", 0), 0), limit))

    if offset is None or offset > max_offset:
        return create_client_error_response("Offset is bigger than maximum offset.")

    query = base.get("q", "").strip()[: Configuration().webserver["max_full_text_search_input_len"]]

    if not query or len(query) < 3:
        total_count = get_all_dms_count()

        if offset > total_count:
            return create_client_error_response("Offset is bigger than the total count.")

        dms = get_all_dms(offset, limit)

    else:
        total_count = get_all_dms_by_query_count(query)

        if offset > total_count:
            return create_client_error_response("Offset is bigger than the total count.")

        dms = get_all_dms_by_query(query, offset, limit)

    props = TDDMsProps(currentPage="artists", count=total_count, limit=limit, dms=dms)

    response = make_response(
        jsonify(
            props=props,
            base=base,
        ),
        200,
    )
    response.headers["Cache-Control"] = "s-maxage=60"

    return response


@v1api_bp.get("/has_pending_dms")
def get_has_pending_dms():
    has_pending_dms = False
    account_id = session.get("account_id")
    if account_id:
        has_pending_dms = has_unapproved_dms(account_id)
    response = make_response(jsonify(has_pending_dms), 200)
    response.headers["Cache-Control"] = "s-maxage=600"
    return response
