"""Partner management endpoints (internal use)."""

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

from ..db import get_db
from ..auth import require_admin_api_key
from ..schemas import PartnerCreate, PartnerCreatedOut
from ..services import partner_service

router = APIRouter(prefix="/v1/partners", tags=["partners"])


@router.post("", response_model=PartnerCreatedOut, status_code=status.HTTP_201_CREATED)
def create_partner(
    payload: PartnerCreate,
    db: Session = Depends(get_db),
    _: None = Depends(require_admin_api_key),
):
    """Create a partner record for onboarding."""

    partner, api_key = partner_service.create_partner(db, payload.name, payload.callback_url)
    return PartnerCreatedOut(
        id=partner.id,
        name=partner.name,
        callback_url=partner.callback_url,
        created_at=partner.created_at,
        api_key=api_key,
    )


@router.post("/{partner_id}/rotate-key", response_model=PartnerCreatedOut)
def rotate_partner_key(
    partner_id: str,
    db: Session = Depends(get_db),
    _: None = Depends(require_admin_api_key),
):
    """Rotate partner API key (admin only)."""

    try:
        partner, api_key = partner_service.rotate_partner_key(db, partner_id)
    except ValueError:
        raise HTTPException(status_code=404, detail="Partner not found")
    return PartnerCreatedOut(
        id=partner.id,
        name=partner.name,
        callback_url=partner.callback_url,
        created_at=partner.created_at,
        api_key=api_key,
    )
