from datetime import date, datetime

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.database import get_db
from app.models.reminder import Reminder
from app.models.user import User
from app.routers.auth import get_current_user
from app.schemas.reminder import ReminderCreate, ReminderListOut, ReminderOut, ReminderUpdate

router = APIRouter(prefix="/api/reminders", tags=["提醒"])


@router.get("", response_model=ReminderListOut)
async def list_reminders(
    date_str: str = Query(...),
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    target_date = date.fromisoformat(date_str)
    start = datetime.combine(target_date, datetime.min.time())
    end = datetime.combine(target_date, datetime.max.time())
    query = (
        select(Reminder)
        .where(Reminder.user_id == current_user.id)
        .where(Reminder.reminder_at >= start)
        .where(Reminder.reminder_at <= end)
        .order_by(Reminder.reminder_at.asc(), Reminder.created_at.asc())
    )
    items = (await db.execute(query)).scalars().all()
    return ReminderListOut(items=items)


@router.post("", response_model=ReminderOut, status_code=201)
async def create_reminder(
    data: ReminderCreate,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    reminder = Reminder(
        user_id=current_user.id,
        title=data.title,
        note=data.note,
        reminder_at=data.reminder_at,
    )
    db.add(reminder)
    await db.commit()
    await db.refresh(reminder)
    return reminder


@router.patch("/{reminder_id}", response_model=ReminderOut)
async def update_reminder(
    reminder_id: str,
    data: ReminderUpdate,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    result = await db.execute(
        select(Reminder).where(Reminder.id == reminder_id, Reminder.user_id == current_user.id)
    )
    reminder = result.scalar_one_or_none()
    if not reminder:
        raise HTTPException(status_code=404, detail="提醒不存在")

    for field, value in data.model_dump(exclude_none=True).items():
        setattr(reminder, field, value)

    await db.commit()
    await db.refresh(reminder)
    return reminder


@router.delete("/{reminder_id}", status_code=204)
async def delete_reminder(
    reminder_id: str,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    result = await db.execute(
        select(Reminder).where(Reminder.id == reminder_id, Reminder.user_id == current_user.id)
    )
    reminder = result.scalar_one_or_none()
    if not reminder:
        raise HTTPException(status_code=404, detail="提醒不存在")

    await db.delete(reminder)
    await db.commit()
