from flask import make_response, jsonify

from src.config import Configuration
from src.internals.cache.redis import get_conn
from src.internals.database.database import query_db
from src.lib.post import is_post_flagged
from src.pages.api.v1 import v1api_bp


@v1api_bp.route("/<service>/user/<creator_id>/post/<post>/flag", methods=["POST"])
def flag_post_api(service, creator_id, post):
    query = """
        INSERT INTO booru_flags (id, "user", service)
        SELECT %s, %s, %s
        WHERE NOT EXISTS (
            SELECT 1
            FROM booru_flags
            WHERE id = %s AND "user" = %s AND service = %s
        )
        RETURNING id, service
    """
    rows_returned = query_db(query, (post, creator_id, service, post, creator_id, service))
    get_conn().set(
        f"is_post_flagged:{service}:{creator_id}:{post}", len(rows_returned), ex=Configuration().redis["default_ttl"]
    )
    status_code = 201 if len(rows_returned) else 409
    response = make_response(jsonify(True), status_code)

    return response


@v1api_bp.route("<service>/user/<creator_id>/post/<post>/flag", methods=["GET"])
def flag_api(service, creator_id, post):
    is_flagged = is_post_flagged(service, creator_id, post)
    status_code = 200 if is_flagged else 404
    response = make_response(jsonify(True), status_code)

    return response
