from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select

from database import get_db
from models import Sample
from schemas import SampleResponse, SampleCreate, SampleUpdate

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


@router.get("/samples", response_model=list[SampleResponse])
async def list_samples(db: AsyncSession = Depends(get_db)):
    result = await db.execute(select(Sample).order_by(Sample.id))
    return result.scalars().all()


@router.get("/samples/{sample_id}", response_model=SampleResponse)
async def get_sample(sample_id: int, db: AsyncSession = Depends(get_db)):
    result = await db.execute(select(Sample).where(Sample.id == sample_id))
    sample = result.scalar_one_or_none()
    if not sample:
        raise HTTPException(status_code=404, detail="Sample not found")
    return sample


@router.post("/samples", response_model=SampleResponse, status_code=201)
async def create_sample(body: SampleCreate, db: AsyncSession = Depends(get_db)):
    sample = Sample(title=body.title, content=body.content, author=body.author)
    db.add(sample)
    await db.commit()
    await db.refresh(sample)
    return sample


@router.put("/samples/{sample_id}", response_model=SampleResponse)
async def update_sample(
    sample_id: int, body: SampleUpdate, db: AsyncSession = Depends(get_db)
):
    result = await db.execute(select(Sample).where(Sample.id == sample_id))
    sample = result.scalar_one_or_none()
    if not sample:
        raise HTTPException(status_code=404, detail="Sample not found")

    if body.title is not None:
        sample.title = body.title
    if body.content is not None:
        sample.content = body.content
    if body.author is not None:
        sample.author = body.author

    await db.commit()
    await db.refresh(sample)
    return sample


@router.delete("/samples/{sample_id}", status_code=204)
async def delete_sample(sample_id: int, db: AsyncSession = Depends(get_db)):
    result = await db.execute(select(Sample).where(Sample.id == sample_id))
    sample = result.scalar_one_or_none()
    if not sample:
        raise HTTPException(status_code=404, detail="Sample not found")
    await db.delete(sample)
    await db.commit()
