"""
Merchant billing method settings endpoints (HWADM-209).
Merchants must configure a billing payment method so HubWallet can collect platform fees.
"""
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

from src.apps.auth.utils.auth import get_current_merchant
from src.apps.pricing_control.crud import get_billing_method, upsert_billing_method
from src.apps.pricing_control.schemas.pricing_schemas import (
    MerchantBillingMethodCreate,
    MerchantBillingMethodResponse,
)
from src.core.database import get_db

router = APIRouter()


@router.get("", tags=["Settings - Billing Method"])
async def get_billing_method_endpoint(
    current_merchant=Depends(get_current_merchant),
    db: Session = Depends(get_db),
):
    method = get_billing_method(db, current_merchant.id)
    if not method:
        return {"billing_method": None}
    return {
        "billing_method": {
            "id": method.id,
            "card_type": method.card_type,
            "masked_card": method.masked_card,
            "billing_name": method.billing_name,
            "is_active": method.is_active,
            "created_at": method.created_at.isoformat() if method.created_at else None,
        }
    }


@router.post("", tags=["Settings - Billing Method"], status_code=status.HTTP_201_CREATED)
async def setup_billing_method(
    body: MerchantBillingMethodCreate,
    current_merchant=Depends(get_current_merchant),
    db: Session = Depends(get_db),
):
    method = upsert_billing_method(db, merchant_id=current_merchant.id, data=body)
    return {
        "billing_method": {
            "id": method.id,
            "card_type": method.card_type,
            "masked_card": method.masked_card,
            "billing_name": method.billing_name,
            "is_active": method.is_active,
            "created_at": method.created_at.isoformat() if method.created_at else None,
        }
    }
