import uuid
from typing import Annotated, Optional
from uuid import UUID
from fastapi import APIRouter, Depends, Header, HTTPException, Query, Response, status
from sqlalchemy.ext.asyncio import AsyncSession
from apps.api.dependencies import get_current_tenant, get_current_user
from shared.schemas import ApiResponse
from infrastructure.database.session import get_db
from modules.billing.schemas import (
    CancelSubscriptionRequest,
    CheckoutOrderRequest,
    CheckoutOrderResponse,
    CouponValidationResponse,
    DowngradeSubscriptionRequest,
    InvoiceResponse,
    PaymentVerificationRequest,
    PaymentVerificationResponse,
    PayWithWalletRequest,
    PlanResponse,
    ReferralResponse,
    RefundRequest,
    RefundResponse,
    SubscriptionResponse,
    TenantUsageResponse,
    UpgradeSubscriptionRequest,
    ValidateCouponRequest,
    WalletResponse,
    WalletTransactionResponse,
)
from modules.billing.service import BillingService
from modules.identity.models import User
from modules.tenants.models import Tenant, TenantMember

router = APIRouter(prefix="/billing", tags=["SaaS Billing & Subscriptions"])


@router.get("/plans", response_model=ApiResponse[list[PlanResponse]], status_code=status.HTTP_200_OK)
async def list_plans(
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Lists available commercial tiers and their entitlement quotas."""
    service = BillingService(db)
    plans = await service.list_plans()
    return ApiResponse(
        message="Available subscription plans retrieved",
        data=plans,
    )


@router.get("/subscription", response_model=ApiResponse[SubscriptionResponse], status_code=status.HTTP_200_OK)
async def get_tenant_subscription(
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Retrieves current subscription status, period dates, and grace period details."""
    tenant, _ = tenant_context
    service = BillingService(db)
    sub = await service.get_tenant_subscription(tenant.id)
    return ApiResponse(
        message="Tenant subscription retrieved",
        data=sub,
    )


@router.post("/checkout", response_model=ApiResponse[CheckoutOrderResponse], status_code=status.HTTP_201_CREATED)
async def create_checkout_order(
    req: CheckoutOrderRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Creates a payment order with Razorpay or Stripe, applying promotional discounts."""
    tenant, _ = tenant_context
    service = BillingService(db)
    order = await service.create_checkout_order(tenant.id, req)
    return ApiResponse(
        message="Checkout order created successfully",
        data=order,
    )


@router.post("/checkout/verify", response_model=ApiResponse[PaymentVerificationResponse], status_code=status.HTTP_200_OK)
async def verify_payment(
    req: PaymentVerificationRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """
    Server-side cryptographic payment verification.
    Validates gateway signatures and activates subscription. Never trusts client claims alone.
    """
    tenant, _ = tenant_context
    service = BillingService(db)
    result = await service.verify_and_activate_payment(tenant.id, req)
    return ApiResponse(
        message=result.message,
        data=result,
    )


@router.post("/wallet/pay", response_model=ApiResponse[PaymentVerificationResponse], status_code=status.HTTP_200_OK)
async def pay_with_wallet(
    req: PayWithWalletRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Pay subscription directly using prepaid wallet balance."""
    tenant, _ = tenant_context
    service = BillingService(db)
    result = await service.pay_with_wallet(tenant.id, req.plan_id, req.coupon_code)
    return ApiResponse(
        message=result.message,
        data=result,
    )


@router.post("/subscription/upgrade", response_model=ApiResponse[CheckoutOrderResponse], status_code=status.HTTP_200_OK)
async def upgrade_subscription(
    req: UpgradeSubscriptionRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Upgrades subscription calculating prorated credit for remaining days."""
    tenant, _ = tenant_context
    service = BillingService(db)
    order = await service.upgrade_subscription(
        tenant.id, req.new_plan_id, req.provider, req.coupon_code
    )
    return ApiResponse(
        message="Upgrade order created with prorated credit",
        data=order,
    )


@router.post("/subscription/downgrade", response_model=ApiResponse[SubscriptionResponse], status_code=status.HTTP_200_OK)
async def downgrade_subscription(
    req: DowngradeSubscriptionRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Downgrades subscription after validating active resource limits."""
    tenant, _ = tenant_context
    service = BillingService(db)
    sub = await service.downgrade_subscription(tenant.id, req.new_plan_id, req.immediate)
    return ApiResponse(
        message="Subscription downgraded successfully",
        data=sub,
    )


@router.post("/subscription/cancel", response_model=ApiResponse[SubscriptionResponse], status_code=status.HTTP_200_OK)
async def cancel_subscription(
    req: CancelSubscriptionRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Cancels subscription either immediately or at current period end."""
    tenant, _ = tenant_context
    service = BillingService(db)
    sub = await service.cancel_subscription(tenant.id, req.immediate)
    return ApiResponse(
        message="Subscription cancellation registered",
        data=sub,
    )


@router.get("/invoices", response_model=ApiResponse[list[InvoiceResponse]], status_code=status.HTTP_200_OK)
async def list_invoices(
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Lists historical and active invoices for the tenant."""
    tenant, _ = tenant_context
    service = BillingService(db)
    invoices = await service.list_invoices(tenant.id)
    return ApiResponse(
        message="Invoices retrieved",
        data=invoices,
    )


@router.get("/invoices/{invoice_id}", response_model=ApiResponse[InvoiceResponse], status_code=status.HTTP_200_OK)
async def get_invoice(
    invoice_id: UUID,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Fetches details of a specific tenant invoice."""
    tenant, _ = tenant_context
    service = BillingService(db)
    invoice = await service.get_invoice(tenant.id, invoice_id)
    return ApiResponse(
        message="Invoice detail retrieved",
        data=invoice,
    )


@router.get("/invoices/{invoice_id}/html", response_class=Response, status_code=status.HTTP_200_OK)
async def render_invoice_html(
    invoice_id: UUID,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Renders a print-ready, professional HTML invoice."""
    tenant, _ = tenant_context
    service = BillingService(db)
    inv = await service.repo.get_invoice_by_id(invoice_id, tenant.id)
    if not inv:
        raise HTTPException(status_code=404, detail="Invoice not found")
    html_content = service.render_invoice_html(inv)
    return Response(content=html_content, media_type="text/html")


@router.post("/refunds", response_model=ApiResponse[RefundResponse], status_code=status.HTTP_200_OK)
async def process_refund(
    req: RefundRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Processes partial or full refund on a paid order."""
    tenant, _ = tenant_context
    service = BillingService(db)
    refund = await service.process_refund(tenant.id, req)
    return ApiResponse(
        message="Refund processed successfully",
        data=refund,
    )


@router.get("/wallet", response_model=ApiResponse[WalletResponse], status_code=status.HTTP_200_OK)
async def get_wallet_balance(
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Retrieves tenant's prepaid credit wallet balance."""
    tenant, _ = tenant_context
    service = BillingService(db)
    wallet = await service.wallets.get_or_create_wallet(tenant.id)
    return ApiResponse(
        message="Wallet balance retrieved",
        data=WalletResponse(
            balance=wallet.balance,
            balance_formatted=f"₹{wallet.balance / 100:.2f}" if wallet.currency == "INR" else f"${wallet.balance / 100:.2f}",
            currency=wallet.currency,
            is_frozen=wallet.is_frozen,
        ),
    )


@router.get("/wallet/transactions", response_model=ApiResponse[list[WalletTransactionResponse]], status_code=status.HTTP_200_OK)
async def get_wallet_transactions(
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Retrieves immutable ledger entries with cryptographic checksums."""
    tenant, _ = tenant_context
    service = BillingService(db)
    txs = await service.wallets.get_transactions(tenant.id)
    return ApiResponse(
        message="Wallet transactions ledger retrieved",
        data=[WalletTransactionResponse.model_validate(t) for t in txs],
    )


@router.post("/coupons/validate", response_model=ApiResponse[CouponValidationResponse], status_code=status.HTTP_200_OK)
async def validate_coupon(
    req: ValidateCouponRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Validates coupon code eligibility and calculates discount."""
    tenant, _ = tenant_context
    service = BillingService(db)
    plan = await service.repo.get_plan_by_id(req.plan_id)
    if not plan:
        raise HTTPException(status_code=404, detail="Plan not found")

    is_valid, coupon, discount, message = await service.coupons.validate_coupon(
        req.code, plan.id, plan.price_amount
    )
    final_amount = max(0, plan.price_amount - discount) if is_valid else plan.price_amount

    return ApiResponse(
        message=message,
        data=CouponValidationResponse(
            is_valid=is_valid,
            code=req.code.upper(),
            discount_type=coupon.discount_type if coupon else "none",
            discount_value=coupon.discount_value if coupon else 0,
            discount_amount=discount,
            final_amount=final_amount,
            message=message,
        ),
    )


@router.get("/referrals", response_model=ApiResponse[ReferralResponse], status_code=status.HTTP_200_OK)
async def get_referrals_stats(
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Retrieves tenant's referral link and rewards earned."""
    tenant, _ = tenant_context
    service = BillingService(db)
    total_ref, total_rewards = await service.repo.count_tenant_referrals(tenant.id)
    ref_code = f"REF-{str(tenant.id)[:8].upper()}"
    return ApiResponse(
        message="Referral stats retrieved",
        data=ReferralResponse(
            referral_code=ref_code,
            referral_link=f"https://dashboard.domain.com/register?ref={ref_code}",
            total_referred=total_ref,
            total_rewarded_credits=total_rewards,
        ),
    )


@router.get("/usage", response_model=ApiResponse[TenantUsageResponse], status_code=status.HTTP_200_OK)
async def get_tenant_usage_and_limits(
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Returns active consumption vs entitlement limits."""
    tenant, _ = tenant_context
    service = BillingService(db)
    usage = await service.entitlements.get_tenant_limits_and_usage(tenant.id)
    return ApiResponse(
        message="Tenant usage and entitlement limits retrieved",
        data=TenantUsageResponse(**usage),
    )
