# ======================================
# == Business logic for stock updates ==
# ======================================

import pandas as pd
from .csv_utils import load_csv, save_csv
from .schemas import StockEvent, AvailabilityRequest, ReservationRequest
from datetime import datetime

def process_stock_event(event: StockEvent):
    inventory = load_csv("mock_inventory.csv")

    # Find matching SKU and warehouse
    mask = (
        (inventory["product_code"] == event.sku) &
        (inventory["warehouse_code"] == event.warehouse_code)
    )

    if not mask.any():
        raise ValueError(f"Product {event.sku} not found in warehouse {event.warehouse_code}")

    # Adjust stock based on event type
    if event.event_type == "receive":
        inventory.loc[mask, "quantity_on_hand"] += event.quantity
    elif event.event_type == "ship":
        inventory.loc[mask, "quantity_on_hand"] -= event.quantity
    elif event.event_type == "adjust":
        inventory.loc[mask, "quantity_on_hand"] = event.quantity

    inventory.loc[mask, "updated_at"] = datetime.utcnow().isoformat()
    save_csv(inventory, "mock_inventory.csv")

    return inventory.loc[mask].to_dict(orient="records")[0]

def check_availability(request: AvailabilityRequest):
    inventory = load_csv("mock_inventory.csv")
    results = []

    for item in request.items:
        sku = item["sku"]
        qty = item["qty"]
        available_qty = inventory.loc[inventory["product_code"] == sku, "quantity_on_hand"].sum()
        results.append({
            "sku": sku,
            "requested": qty,
            "available": available_qty,
            "enough": available_qty >= qty
        })

    all_available = all(r["enough"] for r in results)
    return {"available": all_available, "details": results}

def reserve_inventory(request: ReservationRequest):
    inventory = load_csv("mock_inventory.csv")

    for item in request.items:
        sku = item["sku"]
        qty = item["qty"]
        mask = (
            (inventory["product_code"] == sku) &
            (inventory["warehouse_code"] == request.warehouse_code)
        )
        if not mask.any():
            raise ValueError(f"{sku} not found in {request.warehouse_code}")
        inventory.loc[mask, "reserved_quantity"] += qty
        inventory.loc[mask, "quantity_on_hand"] -= qty

    inventory["updated_at"] = datetime.utcnow().isoformat()
    save_csv(inventory, "mock_inventory.csv")

    return {"status": "reserved", "warehouse": request.warehouse_code, "items": request.items}
