# backend/modules/todo/service.py
from sqlalchemy.orm import Session
from . import models, schemas
from modules.auth.models import User  # Assuming User model is in auth.models
from fastapi import HTTPException, status


def create_todo(db: Session, todo: schemas.TodoCreate, user: User):
    db_todo = models.Todo(**todo.dict(), owner_id=user.id)
    db.add(db_todo)
    db.commit()
    db.refresh(db_todo)
    return db_todo


def get_todos(db: Session, user: User, skip: int = 0, limit: int = 100):
    return (
        db.query(models.Todo)
        .filter(models.Todo.owner_id == user.id)
        .offset(skip)
        .limit(limit)
        .all()
    )


def get_todo(db: Session, todo_id: int, user: User):
    db_todo = (
        db.query(models.Todo)
        .filter(models.Todo.id == todo_id, models.Todo.owner_id == user.id)
        .first()
    )
    if db_todo is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="Todo not found"
        )
    return db_todo


def update_todo(db: Session, todo_id: int, todo_update: schemas.TodoUpdate, user: User):
    db_todo = get_todo(
        db=db, todo_id=todo_id, user=user
    )  # Reuse get_todo to check ownership and existence
    update_data = todo_update.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_todo, key, value)
    db.commit()
    db.refresh(db_todo)
    return db_todo


def delete_todo(db: Session, todo_id: int, user: User):
    db_todo = get_todo(
        db=db, todo_id=todo_id, user=user
    )  # Reuse get_todo to check ownership and existence
    db.delete(db_todo)
    db.commit()
    return db_todo
