from fastapi import APIRouter, HTTPException
from app.core.database import get_connection

router = APIRouter(prefix="/year-locks", tags=["年度锁定"])


@router.get("", summary="年度锁定一覧")
def get_year_locks():
    with get_connection() as conn, conn.cursor() as cur:
        cur.execute("""
            SELECT fiscal_year, is_locked, 
                   (locked_at AT TIME ZONE 'UTC') AT TIME ZONE 'Asia/Tokyo' as locked_at, 
                   locked_by
              FROM year_locks
             ORDER BY fiscal_year
        """)
        return cur.fetchall()


@router.post("/lock", summary="年度锁定")
def lock_year(fiscal_year: int):
    with get_connection() as conn, conn.cursor() as cur:
        cur.execute("""
            INSERT INTO year_locks (fiscal_year, is_locked, locked_at, locked_by)
            VALUES (%s, true, CURRENT_TIMESTAMP AT TIME ZONE 'Asia/Tokyo', %s)
            ON CONFLICT (fiscal_year)
            DO UPDATE
               SET is_locked = true,
                   locked_at = CURRENT_TIMESTAMP AT TIME ZONE 'Asia/Tokyo',
                   locked_by = EXCLUDED.locked_by
        """, (fiscal_year, "system"))
        conn.commit()

    return {"status": "locked", "fiscal_year": fiscal_year}


@router.post("/unlock", summary="年度解锁")
def unlock_year(fiscal_year: int):
    with get_connection() as conn, conn.cursor() as cur:
        cur.execute("""
            UPDATE year_locks
               SET is_locked = false
             WHERE fiscal_year = %s
        """, (fiscal_year,))

        if cur.rowcount == 0:
            raise HTTPException(status_code=404, detail="指定年度不存在")

        conn.commit()

    return {"status": "unlocked", "fiscal_year": fiscal_year}
