"""Stripe checkout for Muleline Cloud plans."""
import logging

import stripe
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse, RedirectResponse

from muleline.config import (
    STRIPE_PRICE_CLOUD,
    STRIPE_PRICE_PRO,
    STRIPE_SECRET_KEY,
    STRIPE_WEBHOOK_SECRET,
)
from muleline.db import get_db

log = logging.getLogger(__name__)
router = APIRouter(tags=["checkout"])

if STRIPE_SECRET_KEY:
    stripe.api_key = STRIPE_SECRET_KEY

PLAN_PRICE_MAP = {
    "cloud": STRIPE_PRICE_CLOUD,
    "pro": STRIPE_PRICE_PRO,
}


@router.post("/api/checkout")
async def create_checkout_session(request: Request):
    if not STRIPE_SECRET_KEY:
        return JSONResponse({"error": "Payment not configured"}, status_code=503)

    try:
        body = await request.json()
    except Exception:
        return JSONResponse({"error": "Invalid request body"}, status_code=400)

    plan = body.get("plan", "")
    price_id = PLAN_PRICE_MAP.get(plan)
    if not price_id:
        return JSONResponse({"error": "Invalid plan"}, status_code=400)

    try:
        base_url = str(request.base_url).rstrip("/")
        session = stripe.checkout.Session.create(
            mode="subscription",
            line_items=[{"price": price_id, "quantity": 1}],
            success_url=f"{base_url}/api/checkout/success?session_id={{CHECKOUT_SESSION_ID}}",
            cancel_url=f"{base_url}/api/checkout/cancel",
        )
        return JSONResponse({"url": session.url})
    except Exception as e:
        log.error("Stripe checkout error: %s", e)
        return JSONResponse({"error": "Checkout failed"}, status_code=500)


@router.get("/api/checkout/success")
async def checkout_success(session_id: str = ""):
    return JSONResponse({"ok": True, "message": "Subscription activated!", "session_id": session_id})


@router.get("/api/checkout/cancel")
async def checkout_cancel():
    return RedirectResponse("/", status_code=302)


@router.post("/api/webhook/stripe")
async def stripe_webhook(request: Request):
    if not STRIPE_WEBHOOK_SECRET:
        return JSONResponse({"error": "Webhook not configured"}, status_code=503)

    payload = await request.body()
    sig_header = request.headers.get("stripe-signature", "")

    try:
        event = stripe.Webhook.construct_event(payload, sig_header, STRIPE_WEBHOOK_SECRET)
    except Exception as e:
        log.error("Stripe webhook signature error: %s", e)
        return JSONResponse({"error": "Invalid signature"}, status_code=400)

    if event["type"] == "checkout.session.completed":
        session = event["data"]["object"]
        customer_email = session.get("customer_email", "")
        subscription_id = session.get("subscription", "")
        log.info("Checkout completed: email=%s subscription=%s", customer_email, subscription_id)
        # TODO: upgrade user tier in DB once Stripe customer ID is linked

    elif event["type"] == "customer.subscription.deleted":
        subscription = event["data"]["object"]
        log.info("Subscription cancelled: %s", subscription.get("id"))
        # TODO: downgrade user tier

    return JSONResponse({"received": True})
