from flask import jsonify, make_response, request

from src.internals.database.database import cached_query
from src.internals.serializers.post import deserialize_post_list, serialize_post_list
from src.lib.posts import get_all_channels_for_server
from src.pages.api.v1 import v1api_bp
from src.utils.utils import parse_int, positive_or_none, step_int


@v1api_bp.get("/discord/channel/lookup/<discord_server>")
def discord_lookup(discord_server):
    channels = get_all_channels_for_server(discord_server)
    response = make_response(jsonify(channels), 200)
    return response


@v1api_bp.get("/discord/channel/<channel_id>")
def discord_channel(channel_id):
    limit = 150
    offset = positive_or_none(step_int(parse_int(request.args.get("o"), 0), limit))
    if offset is None:
        response = make_response(jsonify({"error": "offset not multiple of 150"}), 400)
        return response
    query = "SELECT * FROM discord_posts WHERE channel = %s ORDER BY published desc OFFSET %s LIMIT %s"
    params = (channel_id, offset, limit)
    results = cached_query(
        query, f"discord_posts:{channel_id}:{offset}:{limit}", params, serialize_post_list, deserialize_post_list
    )
    response = make_response(jsonify(results), 200)
    return response
