"""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 ..db import get_db
from ..models import CheckoutSession, Event, Partner
from ..schemas import CheckoutSessionCreate, CheckoutSessionOut

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)):
    """Create a new checkout session for a partner."""
    partner = db.get(Partner, payload.partner_id)
    if not partner:
        raise HTTPException(status_code=404, detail="Partner not found")

    session = CheckoutSession(
        partner_id=payload.partner_id,
        external_order_id=payload.external_order_id,
        amount=payload.amount,
        currency=payload.currency.upper(),
        success_url=payload.success_url,
        cancel_url=payload.cancel_url,
        customer_email=payload.customer_email,
        status="pending",
    )
    db.add(session)
    db.flush()

    event = Event(session_id=session.id, type="created", payload={"status": "pending"})
    db.add(event)
    db.commit()
    db.refresh(session)
    return session


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