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

router = APIRouter(prefix="/month-locks", tags=["月次锁定"])


# ---------- GET：月次锁定一覧 ----------

@router.get("", summary="月次锁定一覧取得")
def get_month_locks():
    with get_connection() as conn, conn.cursor() as cur:
        cur.execute("""
            SELECT
                fiscal_year,
                month,
                is_locked,
                (locked_at AT TIME ZONE 'UTC') AT TIME ZONE 'Asia/Tokyo' as locked_at,
                locked_by
            FROM month_locks
            ORDER BY fiscal_year, month
        """)
        return cur.fetchall()


# ---------- POST：锁定月份 ----------

@router.post("/lock", summary="锁定月份")
def lock_month(fiscal_year: int, month: int):
    # 参数校验
    if not (1 <= month <= 12):
        raise HTTPException(status_code=400, detail="month 必须是 1～12")

    with get_connection() as conn, conn.cursor() as cur:
        cur.execute("""
            INSERT INTO month_locks (
                fiscal_year,
                month,
                is_locked,
                locked_at,
                locked_by
            )
            VALUES (%s, %s, true, CURRENT_TIMESTAMP AT TIME ZONE 'Asia/Tokyo', %s)
            ON CONFLICT (fiscal_year, month)
            DO UPDATE
               SET is_locked = true,
                   locked_at = CURRENT_TIMESTAMP AT TIME ZONE 'Asia/Tokyo',
                   locked_by = EXCLUDED.locked_by
        """, (
            fiscal_year,
            month,
            "system"  # 将来可替换为登录用户
        ))
        conn.commit()

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


# ---------- POST：解锁月份 ----------

@router.post("/unlock", summary="解锁月份")
def unlock_month(fiscal_year: int, month: int):
    # 参数校验
    if not (1 <= month <= 12):
        raise HTTPException(status_code=400, detail="month 必须是 1～12")

    with get_connection() as conn, conn.cursor() as cur:
        cur.execute("""
            UPDATE month_locks
               SET is_locked = false
             WHERE fiscal_year = %s
               AND month = %s
        """, (
            fiscal_year,
            month
        ))

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

        conn.commit()

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