"""
节目期次 API — 增删改查（责编和管理员可操作）
"""

from fastapi import APIRouter, Depends, HTTPException, status
from sqlmodel import Session, select

from app.core.deps import get_current_user, require_role
from app.db.session import get_session
from app.models.episode import Episode
from app.models.user import User, UserRole
from app.schemas.episode import EpisodeCreate, EpisodeResponse, EpisodeUpdate

router = APIRouter(prefix="/api/episodes", tags=["节目期次"])


def require_read_role():
    """GET 接口的鉴权：三个角色都可读"""
    return require_role(UserRole.zhipianren, UserRole.zebian, UserRole.biandao)


@router.get("", response_model=list[EpisodeResponse])
def list_episodes(
    limit: int = 50,
    offset: int = 0,
    session: Session = Depends(get_session),
    current_user: User = Depends(require_read_role()),
):
    """获取节目期次列表（三角色都可读）。按播出日期倒序。"""
    statement = select(Episode).order_by(Episode.air_date.desc()).offset(offset).limit(limit)
    episodes = session.exec(statement).all()
    return episodes


@router.get("/{episode_id}", response_model=EpisodeResponse)
def get_episode(
    episode_id: int,
    session: Session = Depends(get_session),
    current_user: User = Depends(require_read_role()),
):
    """根据 ID 获取单期节目（三角色都可读）。"""
    episode = session.get(Episode, episode_id)
    if episode is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="期次不存在")
    return episode


@router.post("", response_model=EpisodeResponse, status_code=status.HTTP_201_CREATED)
def create_episode(
    body: EpisodeCreate,
    session: Session = Depends(get_session),
    current_user: User = Depends(require_role(UserRole.zhipianren, UserRole.zebian)),
):
    """新增一期节目（仅管理员/责编）。"""
    # 检查期次号唯一
    existing = session.exec(
        select(Episode).where(Episode.episode_number == body.episode_number)
    ).first()
    if existing:
        raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="期次号已存在")

    episode = Episode.model_validate(body.model_dump())
    session.add(episode)
    session.commit()
    session.refresh(episode)
    return episode


@router.patch("/{episode_id}", response_model=EpisodeResponse)
def update_episode(
    episode_id: int,
    body: EpisodeUpdate,
    session: Session = Depends(get_session),
    current_user: User = Depends(require_role(UserRole.zhipianren, UserRole.zebian)),
):
    """更新一期节目信息（仅管理员/责编）。"""
    episode = session.get(Episode, episode_id)
    if episode is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="期次不存在")

    update_data = body.model_dump(exclude_unset=True)
    for field, value in update_data.items():
        setattr(episode, field, value)

    session.add(episode)
    session.commit()
    session.refresh(episode)
    return episode


@router.delete("/{episode_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_episode(
    episode_id: int,
    session: Session = Depends(get_session),
    current_user: User = Depends(require_role(UserRole.zhipianren, UserRole.zebian)),
):
    """删除一期节目（仅管理员/责编）。"""
    episode = session.get(Episode, episode_id)
    if episode is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="期次不存在")
    session.delete(episode)
    session.commit()
    return None