from config import settings
from fastapi import FastAPI, Depends
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import List
from datetime import datetime
from SQLAlchemy import NoteManager
from auth import get_current_user

app = FastAPI(title=settings.TITLE, version=settings.VERSION, debug=settings.DEBUG)

noteManager = NoteManager(settings.DATABASE_URL)

# CORS 配置
app.add_middleware(
    CORSMiddleware,
    allow_credentials=True,
    allow_origin_regex=r"http[s]?://172\.30\.0\..*:5173|http[s]?://.*\.yuany3721\.site|http[s]?://yuany3721\.site",
    allow_methods=["GET", "POST"],
    allow_headers=["*"],
)

# 认证依赖 - 所有路由都需要认证
dependencies = [Depends(get_current_user)]


@app.get("/note/")
async def root():
    return {"api": "note", "message": "Noting backend", "auth": "Protected by Authentik OIDC"}


class PageRequest(BaseModel):
    page: int = 1
    pageSize: int = 10
    name: str
    noteFilter: str = ""
    tagFilter: List[str] = []


@app.post("/note/getByPage", dependencies=dependencies)
async def getByPage(request: PageRequest):
    return noteManager.get_note_by_page(request.name, request.page, request.pageSize, request.noteFilter, request.tagFilter)


class FilterRequest(BaseModel):
    name: str
    noteFilter: str = ""
    tagFilter: List[str] = []


@app.post("/note/getTotal", dependencies=dependencies)
async def getTotal(request: FilterRequest):
    return noteManager.get_total_note_num(request.name, request.noteFilter, request.tagFilter)


@app.post("/note/getAllTags", dependencies=dependencies)
async def getAllTags(request: FilterRequest):
    return noteManager.get_all_tags(request.name, request.noteFilter, request.tagFilter)


class DeleteNoteRequest(BaseModel):
    name: str
    id: int


@app.post("/note/deleteNote", dependencies=dependencies)
async def deleteNote(request: DeleteNoteRequest):
    return noteManager.delete_note(request.name, request.id)


class NewNoteRequest(BaseModel):
    name: str
    content: str
    tags: List[str] = []


@app.post("/note/newNote", dependencies=dependencies)
async def newNote(request: NewNoteRequest):
    return noteManager.create_note(request.name, request.content, request.tags)


class UpdateNoteRequest(BaseModel):
    name: str
    id: int
    content: str
    tags: List[str] = []
    created_at: datetime = datetime.now()


@app.post("/note/updateNote", dependencies=dependencies)
async def updateNote(request: UpdateNoteRequest):
    return noteManager.update_note(request.name, request.id, request.content, request.tags, request.created_at)


if __name__ == "__main__":
    import uvicorn

    uvicorn.run("main:app", host="0.0.0.0", port=7022, reload=settings.DEBUG)
