from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel
from app.core.database import get_connection

router = APIRouter(
    prefix="/opening-balances",
    tags=["期首残高"]
)

class LockRequest(BaseModel):
    fiscal_year: int

@router.get("/lock-status", summary="期首残高確定状態確認")
def get_lock_status(fiscal_year: int = Query(..., description="会計年度")):
    try:
        with get_connection() as conn, conn.cursor() as cur:
            cur.execute("""
                SELECT is_locked
                FROM fiscal_year_locks
                WHERE fiscal_year = %s
            """, (fiscal_year,))
            row = cur.fetchone()
            
            if row:
                return {"is_locked": row[0]}
            else:
                return {"is_locked": False}
    except Exception:
        # テーブルが存在しない場合は未ロック扱い
        return {"is_locked": False}

@router.post("/lock", summary="期首残高年度確定")
def lock_fiscal_year(req: LockRequest):

    with get_connection() as conn, conn.cursor() as cur:
        cur.execute("""
            INSERT INTO fiscal_year_locks (fiscal_year, is_locked)
            VALUES (%s, true)
            ON CONFLICT (fiscal_year)
            DO UPDATE SET
                is_locked = true,
                locked_at = CURRENT_TIMESTAMP AT TIME ZONE 'Asia/Tokyo'
        """, (req.fiscal_year,))
        conn.commit()

    return {"message": "期首残高を確定しました。"}
