from __future__ import annotations

import sqlite3
from typing import Optional

from store_settlement.errors import SettlementError


def inventory_stock_out(
    conn: sqlite3.Connection,
    product_key: str,
    quantity: float,
    *,
    order_id: Optional[str] = None,
    appt_id: Optional[str] = None,
    log_type: str = "sale",
) -> None:
    row = conn.execute(
        "SELECT stock_qty FROM inv_items WHERE key=? AND status='active'",
        (product_key,),
    ).fetchone()
    if not row:
        raise SettlementError("inventory_item_not_found", {"key": product_key})
    before = float(row["stock_qty"] or 0)
    qty = float(quantity)
    if qty <= 0:
        return
    if qty > before:
        raise SettlementError("stock_short", {"key": product_key, "before": before, "need": qty})
    after = before - qty
    conn.execute(
        "UPDATE inv_items SET stock_qty=?, updated_at=datetime('now','localtime') WHERE key=?",
        (after, product_key),
    )
    remark = f"order:{order_id}" if order_id else (f"appt:{appt_id}" if appt_id else "")
    conn.execute(
        """INSERT INTO inv_logs (item_key, direction, type, quantity, before_qty, after_qty,
           ref_appt_id, ref_order_id, remark)
           VALUES (?,?,?,?,?,?,?,?,?)""",
        (
            product_key,
            "out",
            log_type,
            qty,
            before,
            after,
            appt_id,
            order_id,
            remark,
        ),
    )


def inventory_stock_in(
    conn: sqlite3.Connection,
    product_key: str,
    quantity: float,
    order_id: str,
    *,
    typ: str = "refund",
) -> None:
    row = conn.execute(
        "SELECT stock_qty FROM inv_items WHERE key=? AND status='active'",
        (product_key,),
    ).fetchone()
    if not row:
        raise SettlementError("inventory_item_not_found", {"key": product_key})
    before = float(row["stock_qty"] or 0)
    qty = float(quantity)
    after = before + qty
    conn.execute(
        "UPDATE inv_items SET stock_qty=?, updated_at=datetime('now','localtime') WHERE key=?",
        (after, product_key),
    )
    conn.execute(
        """INSERT INTO inv_logs (item_key, direction, type, quantity, before_qty, after_qty,
           ref_order_id, remark)
           VALUES (?,?,?,?,?,?,?,?)""",
        (product_key, "in", typ, qty, before, after, order_id, f"refund:{order_id}"),
    )
