from uuid import UUID
from typing import Optional
from app.modules.inventory.domain.entities import InventoryItem

class InventoryRepository:
    def __init__(self, conn):
        self._conn = conn

    def ensure_schema(self):
        with self._conn.cursor() as cur:
            cur.execute("""
                CREATE SCHEMA IF NOT EXISTS inventory;
                CREATE TABLE IF NOT EXISTS inventory.items (
                    id UUID PRIMARY KEY,
                    material_code TEXT NOT NULL,
                    warehouse_id TEXT NOT NULL,
                    quantity_on_hand NUMERIC(18, 4) NOT NULL,
                    reserved_quantity NUMERIC(18, 4) NOT NULL,
                    version INTEGER DEFAULT 1 -- Dùng cho Optimistic Locking
                );
                CREATE UNIQUE INDEX IF NOT EXISTS idx_inv_mat_wh 
                ON inventory.items(material_code, warehouse_id);
            """)

    def save(self, item: InventoryItem) -> None:
        self.ensure_schema()
        with self._conn.cursor() as cur:
            cur.execute("""
                INSERT INTO inventory.items 
                (id, material_code, warehouse_id, quantity_on_hand, reserved_quantity)
                VALUES (%s, %s, %s, %s, %s)
                ON CONFLICT (id) DO UPDATE SET
                    quantity_on_hand = EXCLUDED.quantity_on_hand,
                    reserved_quantity = EXCLUDED.reserved_quantity,
                    version = inventory.items.version + 1;
            """, (
                str(item.id),
                item.material_code,
                item.warehouse_id,
                item.quantity_on_hand,
                item.reserved_quantity
            ))
