from flask import jsonify, make_response, redirect, request, url_for

from src.lib.favorites import (
    add_favorite_artist,
    add_favorite_post,
    get_favorite_artists,
    get_favorite_posts,
    remove_favorite_artist,
    remove_favorite_post,
)
from src.pages.api.v1 import v1api_bp
from src.types.account.account import Account
from src.utils.decorators import require_login


@v1api_bp.get("/account/favorites")
@require_login
def list_account_favorites(user: Account):
    fave_type = request.args.get("type", "artist")
    if fave_type == "post":
        favorites = get_favorite_posts(user.id)
    else:
        favorites = get_favorite_artists(user.id)

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


@v1api_bp.route("/favorites/post/<service>/<creator_id>/<post_id>", methods=["POST"])
@require_login
def post_favorite_post(service, creator_id, post_id, user: Account):
    add_favorite_post(user.id, service, creator_id, post_id)
    response = make_response(jsonify(True), 200)

    return response


@v1api_bp.route("/favorites/creator/<service>/<creator_id>", methods=["POST"])
@require_login
def post_favorite_artist(service, creator_id, user: Account):
    add_favorite_artist(user.id, service, creator_id)
    response = make_response(jsonify(True), 200)

    return response


@v1api_bp.route("/favorites/post/<service>/<creator_id>/<post_id>", methods=["DELETE"])
@require_login
def delete_favorite_post(service, creator_id, post_id, user: Account):
    remove_favorite_post(user.id, service, creator_id, post_id)
    response = make_response(jsonify(True), 200)

    return response


@v1api_bp.route("/favorites/creator/<service>/<creator_id>", methods=["DELETE"])
@require_login
def delete_favorite_artist(service, creator_id, user: Account):
    remove_favorite_artist(user.id, service, creator_id)
    response = make_response(jsonify(True), 200)

    return response
