from fastapi import APIRouter, HTTPException, Depends
from bson import ObjectId
from ..models import Item
from ..database import get_db
from typing import List

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


@router.post("/", response_model=Item)
async def create_item(item: Item):
  db = get_db()
  item_dict = item.model_dump(exclude={"id"})
  result = db.items.insert_one(item_dict)
  created_item = db.items.find_one({"_id": result.inserted_id})
  return Item.model_validate(created_item)


@router.get("/", response_model=List[Item])
async def read_items():
  db = get_db()
  items = list(db.items.find())
  return [Item.model_validate(item) for item in items]


@router.get("/{item_id}", response_model=Item)
async def read_item(item_id: str):
  db = get_db()
  item = db.items.find_one({"_id": ObjectId(item_id)})
  if item is None:
    raise HTTPException(status_code=404, detail="Item not found")
  return Item.model_validate(item)


@router.put("/{item_id}", response_model=Item)
async def update_item(item_id: str, item: Item):
  db = get_db()
  update_data = item.model_dump(exclude={"id"})
  result = db.items.update_one(
      {"_id": ObjectId(item_id)}, {"$set": update_data})
  if result.modified_count == 0:
    raise HTTPException(status_code=404, detail="Item not found")
  updated_item = db.items.find_one({"_id": ObjectId(item_id)})
  return Item.model_validate(updated_item)


@router.delete("/{item_id}", response_model=dict)
async def delete_item(item_id: str):
  db = get_db()
  result = db.items.delete_one({"_id": ObjectId(item_id)})
  if result.deleted_count == 0:
    raise HTTPException(status_code=404, detail="Item not found")
  return {"message": "Item deleted successfully"}
