from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List

from . import service, schemas
from core.database import get_db
from modules.auth.dependencies import get_current_user
from modules.auth.models import User

router = APIRouter(
    prefix="/todos",
    tags=["todos"],
    dependencies=[Depends(get_current_user)],
    responses={404: {"description": "Not found"}},
)


@router.post("/", response_model=schemas.Todo, status_code=status.HTTP_201_CREATED)
def create_todo_endpoint(
    todo: schemas.TodoCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    return service.create_todo(db=db, todo=todo, user=current_user)


@router.get("/", response_model=List[schemas.Todo])
def read_todos_endpoint(
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    todos = service.get_todos(db=db, user=current_user, skip=skip, limit=limit)
    return todos


@router.get("/{todo_id}", response_model=schemas.Todo)
def read_todo_endpoint(
    todo_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    db_todo = service.get_todo(db=db, todo_id=todo_id, user=current_user)
    if db_todo is None:
        raise HTTPException(status_code=404, detail="Todo not found")
    return db_todo


@router.put("/{todo_id}", response_model=schemas.Todo)
def update_todo_endpoint(
    todo_id: int,
    todo_update: schemas.TodoUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    return service.update_todo(
        db=db, todo_id=todo_id, todo_update=todo_update, user=current_user
    )


@router.delete("/{todo_id}", response_model=schemas.Todo)
def delete_todo_endpoint(
    todo_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    return service.delete_todo(db=db, todo_id=todo_id, user=current_user)
