from typing import List

from app.database import get_session
from app.models import Medication, MedicationUpdate
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from sqlmodel import select

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


@router.post("", response_model=Medication)
async def create_medication(
    *, med: Medication, session: AsyncSession = Depends(get_session)
) -> Medication:
    medication = Medication.from_orm(med)
    session.add(medication)
    await session.commit()
    await session.refresh(medication)
    return medication


@router.get("/{medication_id}", response_model=Medication)
async def retrieve_medication(
    *, medication_id: str, session: AsyncSession = Depends(get_session)
) -> Medication:
    result = await session.execute(
        select(Medication).where(Medication.id == medication_id)
    )
    medication = result.scalar_one_or_none()
    if not medication:
        raise HTTPException(
            status_code=404, detail=f"Medication {medication_id} not found"
        )
    return medication


@router.patch("/{medication_id}", response_model=Medication)
async def update_medication(
    *,
    medication_id: str,
    patch: MedicationUpdate,
    session: AsyncSession = Depends(get_session),
) -> Medication:
    result = await session.execute(
        select(Medication).where(Medication.id == medication_id)
    )
    medication = result.scalar_one_or_none()
    if not medication:
        raise HTTPException(
            status_code=404, detail=f"Medication {medication_id} not found"
        )
    patch_data = patch.dict(exclude_unset=True)
    for key, value in patch_data.items():
        setattr(medication, key, value)
    session.add(medication)
    await session.commit()
    await session.refresh(medication)
    return medication


@router.post("/{medication_id}")
async def delete_medication(
    *, medication_id: str, session: AsyncSession = Depends(get_session)
):
    result = await session.execute(
        select(Medication).where(Medication.id == medication_id)
    )
    medication = result.scalar_one_or_none()
    if not medication:
        raise HTTPException(
            status_code=404, detail=f"Medication {medication_id} not found"
        )
    await session.delete(medication)
    await session.commit()
    return {"ok": True}


@router.get("", response_model=List[Medication])
async def list_medications(
    *, session: AsyncSession = Depends(get_session)
) -> List[Medication]:
    result = await session.execute(select(Medication))
    medications = result.scalars().all()
    return medications

fastapi.HTTPException app.models.Medication.from_orm fastapi.APIRouter sqlmodel.select fastapi.Depends
[((254, 308), 'fastapi.APIRouter', 'APIRouter', ([], {'prefix': '"""/medications"""', 'tags': "['medications']"}), "(prefix='/medications', tags=['medications'])\n", (263, 308), False, 'from fastapi import APIRouter, Depends, HTTPException\n'), ((432, 452), 'fastapi.Depends', 'Depends', (['get_session'], {}), '(get_session)\n', (439, 452), False, 'from fastapi import APIRouter, Depends, HTTPException\n'), ((487, 511), 'app.models.Medication.from_orm', 'Medication.from_orm', (['med'], {}), '(med)\n', (506, 511), False, 'from app.models import Medication, MedicationUpdate\n'), ((770, 790), 'fastapi.Depends', 'Depends', (['get_session'], {}), '(get_session)\n', (777, 790), False, 'from fastapi import APIRouter, Depends, HTTPException\n'), ((1300, 1320), 'fastapi.Depends', 'Depends', (['get_session'], {}), '(get_session)\n', (1307, 1320), False, 'from fastapi import APIRouter, Depends, HTTPException\n'), ((1989, 2009), 'fastapi.Depends', 'Depends', (['get_session'], {}), '(get_session)\n', (1996, 2009), False, 'from fastapi import APIRouter, Depends, HTTPException\n'), ((2501, 2521), 'fastapi.Depends', 'Depends', (['get_session'], {}), '(get_session)\n', (2508, 2521), False, 'from fastapi import APIRouter, Depends, HTTPException\n'), ((997, 1075), 'fastapi.HTTPException', 'HTTPException', ([], {'status_code': '(404)', 'detail': 'f"""Medication {medication_id} not found"""'}), "(status_code=404, detail=f'Medication {medication_id} not found')\n", (1010, 1075), False, 'from fastapi import APIRouter, Depends, HTTPException\n'), ((1528, 1606), 'fastapi.HTTPException', 'HTTPException', ([], {'status_code': '(404)', 'detail': 'f"""Medication {medication_id} not found"""'}), "(status_code=404, detail=f'Medication {medication_id} not found')\n", (1541, 1606), False, 'from fastapi import APIRouter, Depends, HTTPException\n'), ((2202, 2280), 'fastapi.HTTPException', 'HTTPException', ([], {'status_code': '(404)', 'detail': 'f"""Medication {medication_id} not found"""'}), "(status_code=404, detail=f'Medication {medication_id} not found')\n", (2215, 2280), False, 'from fastapi import APIRouter, Depends, HTTPException\n'), ((2580, 2598), 'sqlmodel.select', 'select', (['Medication'], {}), '(Medication)\n', (2586, 2598), False, 'from sqlmodel import select\n'), ((852, 870), 'sqlmodel.select', 'select', (['Medication'], {}), '(Medication)\n', (858, 870), False, 'from sqlmodel import select\n'), ((1383, 1401), 'sqlmodel.select', 'select', (['Medication'], {}), '(Medication)\n', (1389, 1401), False, 'from sqlmodel import select\n'), ((2057, 2075), 'sqlmodel.select', 'select', (['Medication'], {}), '(Medication)\n', (2063, 2075), False, 'from sqlmodel import select\n')]