from fastapi import APIRouter, HTTPException, Depends, Request, BackgroundTasks
from fastapi.responses import JSONResponse
from typing import List, Dict, Union
from app.db import database
from ...models.saas.subscriptions import (
    SubscriptionTypeCreate, SubscriptionType, SubscriptionCreate, 
    Subscription, Payment, SubscriptionUpdate
)
from ...models.saas.usersmodel import User
from ...dependencies.auth import get_current_userdetails
from ...services.saas import subscriptions as saas_service  # Import our services layer
import stripe
import os
from dotenv import load_dotenv

load_dotenv()

router = APIRouter()

# Create a subscription type
@router.post("/subscription-types/", response_model=SubscriptionType)
async def create_subscription_type(
    subscription_type: SubscriptionTypeCreate, 
    db: database.MongoDB = Depends(database.get_mongo_db)
):
    try:
        return await saas_service.create_subscription_type_service(subscription_type, db)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# List subscription types
@router.get("/subscription-types/", response_model=List[SubscriptionType])
async def list_subscription_types(
    db: database.MongoDB = Depends(database.get_mongo_db)
):
    try:
        return await saas_service.list_subscription_types_service(db)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# Get a subscription
@router.get("/subscription/{subscription_id}", response_model=Subscription)
async def get_subscription(
    subscription_id: str, 
    db: database.MongoDB = Depends(database.get_mongo_db)
):
    try:
        return await saas_service.get_subscription_service(subscription_id, db)
    except Exception as e:
        raise HTTPException(status_code=404, detail=str(e))

# Create a subscription
@router.post("/subscribe", response_model=dict)
async def create_subscription(
    subscription: SubscriptionCreate, 
    db: database.MongoDB = Depends(database.get_mongo_db), 
    current_user: User = Depends(get_current_userdetails)
):
    try:
        return await saas_service.create_subscription_service(subscription, db, current_user)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# Update a subscription
@router.post("/update/", response_model=dict)
async def update_subscription(
    subscription: SubscriptionUpdate, 
    db: database.MongoDB = Depends(database.get_mongo_db), 
    current_user: User = Depends(get_current_userdetails)
):
    try:
        return await saas_service.update_subscription_service(subscription, db, current_user)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# Cancel a subscription
@router.post("/cancel_subscription/{subscription_id}", response_model=Subscription)
async def cancel_subscription(
    subscription_id: str, 
    db: database.MongoDB = Depends(database.get_mongo_db), 
    current_user: User = Depends(get_current_userdetails)
):
    try:
        return await saas_service.cancel_subscription_service(subscription_id, db, current_user)
    except Exception as e:
        raise HTTPException(status_code=404, detail=str(e))

# List subscriptions
@router.get("/subscriptions/", response_model=List[Subscription])
async def list_subscriptions(
    db: database.MongoDB = Depends(database.get_mongo_db)
):
    try:
        return await saas_service.list_subscriptions_service(db)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# List payments
@router.get("/payments/", response_model=Dict[str, Union[List[Payment], int]])
async def list_payments(
    db: database.MongoDB = Depends(database.get_mongo_db), 
    current_user: User = Depends(get_current_userdetails)
):
    try:
        return await saas_service.list_payments_service(db, current_user)
    except Exception as e:
        raise HTTPException(status_code=403, detail=str(e))

# Stripe webhook endpoint
@router.post("/stripe-webhook/")
async def stripe_webhook(
    request: Request, 
    background_tasks: BackgroundTasks, 
    db: database.MongoDB = Depends(database.get_mongo_db)
):
    try:
        await saas_service.stripe_webhook_service(request, background_tasks, db)
        return JSONResponse({"status": "success"})
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# Verify Stripe payment
@router.post("/stripe/verify")
async def verify_payment(request: Request):
    body = await request.json()
    session_id = body.get("session_id")
    if not session_id:
        raise HTTPException(status_code=400, detail="Session ID is required")
    try:
        result = await saas_service.verify_payment_service(session_id)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# Create Stripe portal session
@router.post("/stripe/portal/")
async def create_portal_session(
    request: Request, 
    db: database.MongoDB = Depends(database.get_mongo_db)
):
    body = await request.json()
    subscription_id = body.get("subscription_id")
    if not subscription_id:
        raise HTTPException(status_code=400, detail="Subscription ID is required.")
    try:
        result = await saas_service.create_portal_session_service(subscription_id, db)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
