from datetime import datetime

from fastapi import APIRouter, Depends
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session

from app.database import get_db
from app.models.user import User
from app.models.user_note import UserNote
from app.utils.auth import get_current_user

router = APIRouter()


class MyNoteResponse(BaseModel):
    content: str
    updated_at: datetime | None = None


class MyNoteUpdate(BaseModel):
    content: str = Field(default="", max_length=50000)


@router.get("", response_model=MyNoteResponse)
def get_my_note(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    note = db.query(UserNote).filter(UserNote.user_id == current_user.id).first()
    if not note:
        return {"content": "", "updated_at": None}
    return {"content": note.content or "", "updated_at": note.updated_at}


@router.put("", response_model=MyNoteResponse)
def save_my_note(
    data: MyNoteUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    note = db.query(UserNote).filter(UserNote.user_id == current_user.id).first()
    if not note:
        note = UserNote(user_id=current_user.id, content=data.content)
        db.add(note)
    else:
        note.content = data.content
        note.updated_at = datetime.utcnow()
    db.commit()
    db.refresh(note)
    return {"content": note.content or "", "updated_at": note.updated_at}
