import logging

from flask import Blueprint, flash, redirect, render_template, request, session, url_for

from app.auth import get_active_account, get_auth_url, save_account_from_login
from app.models import Account
from app.services.errors import ServiceError
from app.tiktok_api import TikTokAPIError

auth_bp = Blueprint("auth", __name__)
log = logging.getLogger(__name__)


@auth_bp.route("/")
def index():
    if get_active_account():
        return redirect(url_for("account.dashboard"))
    return redirect(url_for("auth.login"))


@auth_bp.route("/login")
def login():
    return render_template("login.html")


@auth_bp.route("/auth/start")
def auth_start():
    return redirect(get_auth_url())


@auth_bp.route("/auth/callback")
def auth_callback():
    code = request.args.get("code")
    state = request.args.get("state")
    error = request.args.get("error_description") or request.args.get("error")
    if error:
        log.warning("auth.callback refused error_param_present")
        flash("TikTok login was refused. Try again.", "error")
        return redirect(url_for("auth.login"))
    try:
        account = save_account_from_login(code, state)
    except ServiceError as e:
        flash(e.message, "error")
        return redirect(url_for("auth.login"))
    except TikTokAPIError as e:
        log.error("auth.callback failed", exc_info=True)
        flash(e.message, "error")
        return redirect(url_for("auth.login"))
    except Exception:
        log.error("auth.callback failed", exc_info=True)
        flash("Could not complete TikTok login. Try again.", "error")
        return redirect(url_for("auth.login"))

    session["active_account_id"] = account.id
    flash(f"Connected {account.display_name}.", "success")
    return redirect(url_for("account.dashboard"))


@auth_bp.route("/logout", methods=["POST"])
def logout():
    session.clear()
    flash("Signed out.", "info")
    return redirect(url_for("auth.login"))
