"""Customer satisfaction rating endpoints."""
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from database import get_db
from models import Rating, RatingCreate, RatingOut, SRRequest

router = APIRouter(prefix="/api/rating", tags=["rating"])


@router.post("/{sr_id}", response_model=RatingOut, status_code=201)
async def submit_rating(sr_id: str, payload: RatingCreate,
                         db: AsyncSession = Depends(get_db)):
    if not 1 <= payload.stars <= 5:
        raise HTTPException(400, "별점은 1~5 사이여야 합니다.")

    # 중복 방지
    existing = await db.execute(select(Rating).where(Rating.sr_id == sr_id))
    if existing.scalars().first():
        raise HTTPException(409, "이미 평가가 등록된 SR입니다.")

    r = await db.execute(select(SRRequest).where(SRRequest.sr_id == sr_id))
    if not r.scalars().first():
        raise HTTPException(404, "SR을 찾을 수 없습니다.")

    rating = Rating(sr_id=sr_id, **payload.model_dump())
    db.add(rating)
    await db.commit()
    await db.refresh(rating)
    return rating


@router.get("/{sr_id}", response_model=RatingOut)
async def get_rating(sr_id: str, db: AsyncSession = Depends(get_db)):
    result = await db.execute(select(Rating).where(Rating.sr_id == sr_id))
    rating = result.scalars().first()
    if not rating:
        raise HTTPException(404, "평가 정보가 없습니다.")
    return rating
