"""Checkout session API routes.

These endpoints allow partners to create a payment session and later
retrieve its status. This is the minimal API surface needed for Phase 1.
"""

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

from ..auth import get_partner_from_api_key, require_admin_api_key
from ..db import get_db
from ..models import Partner
from ..schemas import CheckoutSessionCreate, CheckoutSessionOut, PayoutUpdateIn
from ..services import checkout_service

router = APIRouter(prefix="/v1/checkout-sessions", tags=["checkout"])


@router.post("", response_model=CheckoutSessionOut, status_code=status.HTTP_201_CREATED)
def create_checkout_session(
    payload: CheckoutSessionCreate,
    db: Session = Depends(get_db),
    partner: Partner = Depends(get_partner_from_api_key),
):
    """Create a new checkout session for a partner."""
    if payload.partner_id and payload.partner_id != partner.id:
        raise HTTPException(status_code=403, detail="Partner mismatch")

    session = checkout_service.create_session(db, partner, payload)
    return session


@router.get("/{session_id}", response_model=CheckoutSessionOut)
def get_checkout_session(
    session_id: str,
    db: Session = Depends(get_db),
    partner: Partner = Depends(get_partner_from_api_key),
):
    """Fetch a checkout session by its ID."""
    session = checkout_service.get_session_for_partner(db, session_id, partner)
    if not session:
        raise HTTPException(status_code=404, detail="Checkout session not found")
    return session


@router.post("/{session_id}/payout", response_model=CheckoutSessionOut)
def update_payout_status(
    session_id: str,
    payload: PayoutUpdateIn,
    db: Session = Depends(get_db),
    _: None = Depends(require_admin_api_key),
):
    """Update payout tracking fields for a session (admin only)."""

    session = checkout_service.get_session(db, session_id)
    if not session:
        raise HTTPException(status_code=404, detail="Checkout session not found")
    return checkout_service.update_payout(db, session, payload)
