from flask import Blueprint, make_response, redirect, render_template, request, url_for

from src.lib.dms import approve_dms, cleanup_unapproved_dms, get_unapproved_dms, clean_dms_already_approved
from src.pages.imports.types import DMPageProps
from src.types.account.account import Account
from src.types.props import SuccessProps
from src.utils.decorators import require_login

review_dms_bp = Blueprint("review_dms", __name__)


@review_dms_bp.get("/account/review_dms")
@require_login
def importer_dms(user: Account):
    account_id_int = int(user.id)
    status = "ignored" if request.args.get("status") == "ignored" else "pending"
    dms = get_unapproved_dms(account_id_int, request.args.get("status") == "ignored")

    props = DMPageProps(account_id=account_id_int, dms=dms, status=status)

    response = make_response(
        render_template(
            "review_dms/review_dms.html",
            props=props,
        ),
        200,
    )

    response.headers["Cache-Control"] = "max-age=0, private, must-revalidate"
    return response


@review_dms_bp.post("/account/review_dms")
@require_login
def approve_importer_dms(user: Account):
    props = SuccessProps(currentPage="import", redirect="/account/review_dms")
    approved_hashes = request.form.getlist("approved_hashes")
    delete_ignored = bool(request.form.get("delete_ignored", default=False))
    approve_dms(int(user.id), approved_hashes)
    clean_dms_already_approved(int(user.id))
    cleanup_unapproved_dms(int(user.id))
    if delete_ignored:
        cleanup_unapproved_dms(int(user.id), delete=True)

    response = make_response(render_template("success.html", props=props), 200)
    response.headers["Cache-Control"] = "max-age=0, private, must-revalidate"
    return response
