import json
import secrets
from datetime import datetime, timezone
from typing import Any
from services.cart_service import validate_coupon
from services.settings_service import get_int_setting, get_store_settings
from utils.db import get_db, transaction
from utils.formatting import format_inr, parse_json_safe
from utils.security import log_admin_action

ORDER_STATUSES = [
    "Pending Payment",
    "Payment Verification Pending",
    "Payment Verified",
    "Order Confirmed",
    "Processing",
    "Packed",
    "Shipped",
    "Out for Delivery",
    "Delivered",
    "Cancelled",
    "Refund Requested",
    "Refunded",
]

ALLOWED_ADMIN_TRANSITIONS = {
    "Pending Payment": ["Payment Verification Pending", "Payment Verified", "Cancelled"],
    "Payment Verification Pending": ["Payment Verified", "Pending Payment", "Cancelled"],
    "Payment Verified": ["Order Confirmed", "Processing", "Packed", "Shipped", "Out for Delivery", "Delivered", "Cancelled"],
    "Order Confirmed": ["Processing", "Packed", "Shipped", "Out for Delivery", "Delivered", "Cancelled"],
    "Processing": ["Packed", "Shipped", "Out for Delivery", "Delivered", "Cancelled"],
    "Packed": ["Shipped", "Out for Delivery", "Delivered", "Cancelled"],
    "Shipped": ["Out for Delivery", "Delivered"],
    "Out for Delivery": ["Delivered"],
    "Delivered": [],
    "Refund Requested": ["Refunded", "Delivered"],
    "Cancelled": [],
    "Refunded": [],
}


GARAGE_LOCKED_DISPATCH_STATUSES = {"Shipped", "Out for Delivery", "Delivered"}


def order_garage_dispatch_allowed(conn, order_row) -> bool:
    """Return True if order is not a Garage Hold or customer has requested dispatch from /garage."""
    if not order_row or (order_row["fulfillment_mode"] or "") != "garage_hold":
        return True
    holds = conn.execute(
        "SELECT hold_status FROM garage_holds WHERE order_id = ?",
        (order_row["id"],),
    ).fetchall()
    if not holds:
        return False
    return all(h["hold_status"] in ("dispatch_requested", "dispatched") for h in holds)


def get_allowed_admin_transitions(current_status: str, order=None, db=None) -> list[str]:
    allowed = list(ALLOWED_ADMIN_TRANSITIONS.get(current_status, []))
    if order and (order.get("fulfillment_mode") or "") == "garage_hold":
        conn = db or get_db()
        if not order_garage_dispatch_allowed(conn, order):
            allowed = [st for st in allowed if st not in GARAGE_LOCKED_DISPATCH_STATUSES]
    return allowed


def _generate_order_number(conn) -> str:
    prefix = datetime.now(timezone.utc).strftime("DWI-%y%m%d")
    for _ in range(10):
        cand = f"{prefix}-{secrets.randbelow(900000) + 100000}"
        exists = conn.execute("SELECT 1 FROM orders WHERE order_number = ?", (cand,)).fetchone()
        if not exists:
            return cand
    return f"DWI-{secrets.token_hex(4).upper()}"


def create_order_from_cart(
    *,
    cart_id: int,
    customer_id: int | None,
    customer_name: str,
    customer_email: str,
    customer_phone: str,
    shipping_address: dict,
    billing_address: dict | None,
    fulfillment_mode: str,
    payment_method: str,
    utr_number: str = "",
    proof_file_info: tuple[str, str, str, int] | None = None,
    coupon_code: str = "",
    notes: str = "",
) -> dict[str, Any]:
    """Create an order atomically from the database cart.

    proof_file_info: optional (stored_rel_path, original_filename, mime_type, file_size)
    """
    if fulfillment_mode not in ("standard", "garage_hold", "pre_order"):
        fulfillment_mode = "standard"

    clean_phone = "".join(ch for ch in (customer_phone or "") if ch.isdigit())
    if len(clean_phone) < 10:
        raise ValueError("Please provide a valid 10-digit mobile number.")
    if not customer_name.strip():
        raise ValueError("Full name is required.")
    if not shipping_address.get("address_line1") or not shipping_address.get("city") or not shipping_address.get("pincode"):
        raise ValueError("Complete shipping address, city, and pincode are required.")

    if fulfillment_mode == "garage_hold" and not customer_id:
        raise ValueError("Please sign in or register a customer account to use Collector Garage Hold.")

    settings = get_store_settings()
    flat_shipping = get_int_setting(settings, "shipping_charge_paise", 9900)
    upi_id = settings.get("upi_id", "9022676722@okaxis")

    with transaction() as conn:
        cart_row = conn.execute("SELECT * FROM carts WHERE id = ?", (cart_id,)).fetchone()
        if not cart_row:
            raise ValueError("Cart not found.")

        rows = conn.execute(
            """
            SELECT ci.id AS cart_item_id, ci.product_id, ci.quantity, ci.purchase_mode,
                   p.sku, p.name, p.scale, p.price_paise, p.mrp_paise,
                   p.is_pre_order, p.pre_order_token_paise, p.pre_order_allocation,
                   p.pre_order_reserved_count, p.pre_order_limit_per_customer,
                   p.expected_arrival_date, p.pre_order_closing_date,
                   p.garage_hold_eligible, p.is_sold_out, p.availability_status, p.is_visible,
                   b.name AS brand_name,
                   COALESCE(i.stock_qty, 0) AS stock_qty,
                   COALESCE(i.reserved_qty, 0) AS reserved_qty,
                   COALESCE(
                       (SELECT image_url FROM product_images pi WHERE pi.product_id = p.id ORDER BY pi.is_primary DESC, pi.sort_order ASC, pi.id ASC LIMIT 1),
                       '/static/assets/images/logo.png'
                   ) AS image_url
            FROM cart_items ci
            JOIN products p ON p.id = ci.product_id
            JOIN brands b ON b.id = p.brand_id
            LEFT JOIN inventory i ON i.product_id = p.id
            WHERE ci.cart_id = ?
            ORDER BY ci.id ASC
            """,
            (cart_id,),
        ).fetchall()

        if not rows:
            raise ValueError("Your cart is empty.")

        subtotal_paise = 0
        prepared_items = []
        has_preorder_item = False
        has_standard_item = False

        for r in rows:
            qty = int(r["quantity"])
            if not r["is_visible"]:
                raise ValueError(f"{r['name']} is no longer available.")

            is_token = bool(r["is_pre_order"] or r["purchase_mode"] == "pre_order_token")
            if is_token:
                has_preorder_item = True
                if r["pre_order_closing_date"]:
                    closed = conn.execute(
                        "SELECT date('now') > date(?) AS c", (r["pre_order_closing_date"],)
                    ).fetchone()["c"]
                    if closed:
                        raise ValueError(f"Pre-order window closed for {r['name']}.")
                alloc = int(r["pre_order_allocation"] or 0)
                if alloc > 0:
                    rem = alloc - int(r["pre_order_reserved_count"] or 0)
                    if qty > rem:
                        raise ValueError(f"Insufficient pre-order allocation for {r['name']} ({rem} left).")
                else:
                    avail = int(r["stock_qty"]) - int(r["reserved_qty"])
                    if qty > avail:
                        raise ValueError(f"Insufficient stock for {r['name']} ({avail} left).")

                limit_per = int(r["pre_order_limit_per_customer"] or 2)
                prior_qty = 0
                if customer_id:
                    prior_qty = conn.execute(
                        """
                        SELECT COALESCE(SUM(poi.quantity), 0)
                        FROM pre_order_items poi
                        JOIN pre_orders po ON po.id = poi.pre_order_id
                        WHERE po.customer_id = ? AND poi.product_id = ? AND po.status NOT IN ('Cancelled', 'Refunded')
                        """,
                        (customer_id, r["product_id"]),
                    ).fetchone()[0]
                if prior_qty + qty > limit_per:
                    raise ValueError(
                        f"Pre-order limit for {r['name']} is {limit_per} per collector."
                    )

                unit_price_paise = int(r["pre_order_token_paise"] or 0) or int(r["price_paise"])
                full_price_paise = int(r["price_paise"])
                balance_due_paise = max(0, full_price_paise - unit_price_paise) * qty
            else:
                has_standard_item = True
                if r["is_sold_out"] or r["availability_status"] == "sold_out":
                    raise ValueError(f"{r['name']} is sold out.")
                if fulfillment_mode == "garage_hold" and not r["garage_hold_eligible"]:
                    raise ValueError(f"{r['name']} is not eligible for Collector Garage Hold.")
                avail = int(r["stock_qty"]) - int(r["reserved_qty"])
                if qty > avail:
                    raise ValueError(f"Only {avail} unit(s) left for {r['name']}.")
                unit_price_paise = int(r["price_paise"])
                full_price_paise = unit_price_paise
                balance_due_paise = 0

            line_total_paise = unit_price_paise * qty
            subtotal_paise += line_total_paise
            prepared_items.append(
                {
                    "row": r,
                    "qty": qty,
                    "is_token": is_token,
                    "unit_price_paise": unit_price_paise,
                    "full_price_paise": full_price_paise,
                    "balance_due_paise": balance_due_paise,
                    "line_total_paise": line_total_paise,
                }
            )

        effective_mode = fulfillment_mode
        if has_preorder_item and not has_standard_item and effective_mode == "standard":
            effective_mode = "pre_order"

        # Validate coupon server-side
        code_to_use = (coupon_code or cart_row["coupon_code"] or "").strip()
        coupon_id = None
        coupon_code_snap = ""
        discount_paise = 0
        if code_to_use:
            c_info = validate_coupon(
                code_to_use,
                subtotal_paise,
                customer_id=customer_id,
                customer_phone=clean_phone,
            )
            coupon_id = c_info["coupon_id"]
            coupon_code_snap = c_info["code"]
            discount_paise = c_info["discount_paise"]

        discounted_subtotal = max(0, subtotal_paise - discount_paise)
        if effective_mode in ("garage_hold", "pre_order") or (has_preorder_item and not has_standard_item):
            shipping_paise = 0
        else:
            shipping_paise = flat_shipping

        total_paise = discounted_subtotal + shipping_paise

        has_proof = proof_file_info is not None
        initial_order_status = "Payment Verification Pending" if has_proof else "Pending Payment"
        initial_payment_status = "Verification Pending" if has_proof else "Pending"

        order_number = _generate_order_number(conn)
        tracking_token = secrets.token_urlsafe(16)
        shipping_snap = {
            "flat_shipping_paise": flat_shipping,
            "free_shipping_threshold_paise": 0,
            "applied_shipping_paise": shipping_paise,
            "fulfillment_mode": effective_mode,
        }

        cur = conn.execute(
            """
            INSERT INTO orders (
                order_number, tracking_token, customer_id, customer_name, customer_email,
                customer_phone, shipping_address_json, billing_address_json, fulfillment_mode,
                status, subtotal_paise, discount_paise, shipping_paise, total_paise,
                coupon_id, coupon_code_snapshot, shipping_rule_snapshot_json, notes
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            """,
            (
                order_number,
                tracking_token,
                customer_id,
                customer_name.strip(),
                (customer_email or "").strip(),
                clean_phone,
                json.dumps(shipping_address),
                json.dumps(billing_address or shipping_address),
                effective_mode,
                initial_order_status,
                subtotal_paise,
                discount_paise,
                shipping_paise,
                total_paise,
                coupon_id,
                coupon_code_snap,
                json.dumps(shipping_snap),
                (notes or "").strip(),
            ),
        )
        order_id = cur.lastrowid

        preorder_items_created = []
        total_po_token_paise = 0
        total_po_balance_paise = 0

        for item in prepared_items:
            r = item["row"]
            qty = item["qty"]
            hold_req = 1 if (effective_mode == "garage_hold" and not item["is_token"]) else 0

            oi_cur = conn.execute(
                """
                INSERT INTO order_items (
                    order_id, product_id, sku_snapshot, product_name_snapshot,
                    brand_snapshot, scale_snapshot, image_snapshot, quantity,
                    unit_price_paise, mrp_paise, line_total_paise,
                    is_pre_order_token, full_price_paise, balance_due_paise, garage_hold_requested
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                """,
                (
                    order_id,
                    r["product_id"],
                    r["sku"],
                    r["name"],
                    r["brand_name"],
                    r["scale"],
                    r["image_url"],
                    qty,
                    item["unit_price_paise"],
                    int(r["mrp_paise"]),
                    item["line_total_paise"],
                    1 if item["is_token"] else 0,
                    item["full_price_paise"],
                    item["balance_due_paise"],
                    hold_req,
                ),
            )
            order_item_id = oi_cur.lastrowid

            # Reserve stock atomically
            if item["is_token"]:
                if int(r["pre_order_allocation"] or 0) > 0:
                    upd = conn.execute(
                        """
                        UPDATE products
                        SET pre_order_reserved_count = pre_order_reserved_count + ?,
                            updated_at = datetime('now')
                        WHERE id = ? AND (pre_order_allocation - pre_order_reserved_count) >= ?
                        """,
                        (qty, r["product_id"], qty),
                    )
                    if upd.rowcount == 0:
                        raise ValueError(f"Pre-order allocation exhausted for {r['name']}.")
                else:
                    upd = conn.execute(
                        """
                        UPDATE inventory
                        SET reserved_qty = reserved_qty + ?, updated_at = datetime('now')
                        WHERE product_id = ? AND (stock_qty - reserved_qty) >= ?
                        """,
                        (qty, r["product_id"], qty),
                    )
                    if upd.rowcount == 0:
                        raise ValueError(f"Insufficient stock for {r['name']}.")
                preorder_items_created.append((r, order_item_id, item))
                total_po_token_paise += item["line_total_paise"]
                total_po_balance_paise += item["balance_due_paise"]
            else:
                upd = conn.execute(
                    """
                    UPDATE inventory
                    SET reserved_qty = reserved_qty + ?, updated_at = datetime('now')
                    WHERE product_id = ? AND (stock_qty - reserved_qty) >= ?
                    """,
                    (qty, r["product_id"], qty),
                )
                if upd.rowcount == 0:
                    raise ValueError(f"Insufficient stock for {r['name']}.")

                inv_now = conn.execute(
                    "SELECT stock_qty, reserved_qty FROM inventory WHERE product_id = ?",
                    (r["product_id"],),
                ).fetchone()
                avail_after = int(inv_now["stock_qty"]) - int(inv_now["reserved_qty"])
                conn.execute(
                    """
                    INSERT INTO inventory_history (
                        product_id, change_qty, previous_qty, new_qty, change_type,
                        reference_type, reference_id, note, actor_type, actor_id
                    ) VALUES (?, ?, ?, ?, 'order_reserve', 'order', ?, ?, 'customer', ?)
                    """,
                    (
                        r["product_id"],
                        -qty,
                        avail_after + qty,
                        avail_after,
                        order_number,
                        f"Reserved {qty} unit(s) for order {order_number}",
                        customer_id,
                    ),
                )

                if hold_req and customer_id:
                    gh_cur = conn.execute(
                        """
                        INSERT INTO garage_holds (
                            customer_id, order_id, order_item_id, product_id, quantity, hold_status
                        ) VALUES (?, ?, ?, ?, ?, 'pending_payment')
                        """,
                        (customer_id, order_id, order_item_id, r["product_id"], qty),
                    )
                    conn.execute(
                        """
                        INSERT INTO garage_hold_history (garage_hold_id, action, note, actor_type, actor_id)
                        VALUES (?, 'created', ?, 'customer', ?)
                        """,
                        (gh_cur.lastrowid, f"Hold created via order {order_number} (awaiting payment verification)", customer_id),
                    )

        # Pre-order header record
        if preorder_items_created:
            po_cur = conn.execute(
                """
                INSERT INTO pre_orders (
                    order_id, customer_id, customer_name, customer_phone, customer_email,
                    status, total_token_paise, total_balance_paise
                ) VALUES (?, ?, ?, ?, ?, 'Pending Token Payment', ?, ?)
                """,
                (
                    order_id,
                    customer_id,
                    customer_name.strip(),
                    clean_phone,
                    (customer_email or "").strip(),
                    total_po_token_paise,
                    total_po_balance_paise,
                ),
            )
            pre_order_id = po_cur.lastrowid
            for r, oi_id, item in preorder_items_created:
                conn.execute(
                    """
                    INSERT INTO pre_order_items (
                        pre_order_id, product_id, order_item_id, quantity,
                        token_unit_paise, full_unit_paise, balance_unit_paise,
                        expected_arrival_date, item_status
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'reserved')
                    """,
                    (
                        pre_order_id,
                        r["product_id"],
                        oi_id,
                        item["qty"],
                        item["unit_price_paise"],
                        item["full_price_paise"],
                        max(0, item["full_price_paise"] - item["unit_price_paise"]),
                        r["expected_arrival_date"],
                    ),
                )

        # Record coupon usage
        if coupon_id:
            conn.execute(
                """
                INSERT INTO coupon_usage (coupon_id, order_id, customer_id, customer_phone, discount_applied_paise)
                VALUES (?, ?, ?, ?, ?)
                """,
                (coupon_id, order_id, customer_id, clean_phone, discount_paise),
            )
            conn.execute(
                "UPDATE coupons SET times_used = times_used + 1, updated_at = datetime('now') WHERE id = ?",
                (coupon_id,),
            )

        # Payment record (NEVER auto-verified)
        pay_cur = conn.execute(
            """
            INSERT INTO payments (
                order_id, payment_method, amount_paise, upi_id_used, utr_number, status
            ) VALUES (?, ?, ?, ?, ?, ?)
            """,
            (
                order_id,
                payment_method or "UPI App",
                total_paise,
                upi_id,
                (utr_number or "").strip(),
                initial_payment_status,
            ),
        )
        payment_id = pay_cur.lastrowid

        if proof_file_info is not None:
            rel_path, orig_name, mime_type, file_size = proof_file_info
            conn.execute(
                """
                INSERT INTO payment_proofs (
                    payment_id, order_id, file_path, original_filename, mime_type, file_size,
                    utr_number, uploaded_by_customer_id, verification_action
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'submitted')
                """,
                (
                    payment_id,
                    order_id,
                    rel_path,
                    orig_name,
                    mime_type,
                    file_size,
                    (utr_number or "").strip(),
                    customer_id,
                ),
            )

        # Shipping shell row
        conn.execute("INSERT INTO shipping (order_id) VALUES (?)", (order_id,))

        # Initial order status history row
        conn.execute(
            """
            INSERT INTO order_status_history (
                order_id, status, note, updated_by_type, updated_by_id, updated_by_name
            ) VALUES (?, ?, ?, 'customer', ?, ?)
            """,
            (
                order_id,
                initial_order_status,
                "Order created with payment proof awaiting admin verification."
                if has_proof
                else "Order created. Awaiting manual UPI payment and proof upload.",
                customer_id,
                customer_name.strip(),
            ),
        )

        # Auto-save customer's shipping address for future checkouts if not already saved
        if customer_id:
            a1 = (shipping_address.get("address_line1") or "").strip()
            a2 = (shipping_address.get("address_line2") or "").strip()
            ct = (shipping_address.get("city") or "").strip()
            st = (shipping_address.get("state") or "").strip()
            pc = (shipping_address.get("pincode") or "").strip()
            if a1 and ct and pc:
                dup_addr = conn.execute(
                    """
                    SELECT id FROM addresses
                    WHERE customer_id = ? AND address_line1 = ? COLLATE NOCASE
                      AND city = ? COLLATE NOCASE AND pincode = ?
                    LIMIT 1
                    """,
                    (customer_id, a1, ct, pc),
                ).fetchone()
                if not dup_addr:
                    has_any = conn.execute(
                        "SELECT 1 FROM addresses WHERE customer_id = ? LIMIT 1",
                        (customer_id,),
                    ).fetchone()
                    conn.execute(
                        """
                        INSERT INTO addresses (
                            customer_id, label, recipient_name, phone,
                            address_line1, address_line2, city, state, pincode, is_default
                        ) VALUES (?, 'Default', ?, ?, ?, ?, ?, ?, ?, ?)
                        """,
                        (
                            customer_id,
                            (shipping_address.get("recipient_name") or customer_name).strip(),
                            clean_phone,
                            a1,
                            a2,
                            ct,
                            st,
                            pc,
                            0 if has_any else 1,
                        ),
                    )

        # Clear cart
        conn.execute("DELETE FROM cart_items WHERE cart_id = ?", (cart_id,))
        conn.execute("UPDATE carts SET coupon_code = '', updated_at = datetime('now') WHERE id = ?", (cart_id,))

        return {
            "order_id": order_id,
            "order_number": order_number,
            "tracking_token": tracking_token,
            "status": initial_order_status,
            "total_paise": total_paise,
            "total_formatted": format_inr(total_paise),
            "customer_name": customer_name.strip(),
            "customer_phone": clean_phone,
        }


def attach_payment_proof_to_order(
    *,
    order_id: int,
    customer_id: int | None,
    utr_number: str,
    payment_method: str,
    proof_file_info: tuple[str, str, str, int],
) -> None:
    rel_path, orig_name, mime_type, file_size = proof_file_info
    with transaction() as conn:
        order = conn.execute("SELECT * FROM orders WHERE id = ?", (order_id,)).fetchone()
        if not order:
            raise ValueError("Order not found.")
        if order["status"] in ("Cancelled", "Refunded", "Delivered"):
            raise ValueError(f"Order is {order['status']} and cannot accept new payment proofs.")
        pay = conn.execute("SELECT * FROM payments WHERE order_id = ? ORDER BY id DESC LIMIT 1", (order_id,)).fetchone()
        if not pay:
            raise ValueError("Payment record not found.")
        if pay["status"] == "Verified":
            raise ValueError("Payment is already verified for this order.")

        conn.execute(
            """
            UPDATE payments
            SET payment_method = ?, utr_number = ?, status = 'Verification Pending', updated_at = datetime('now')
            WHERE id = ?
            """,
            (payment_method or pay["payment_method"], (utr_number or "").strip(), pay["id"]),
        )
        conn.execute(
            """
            INSERT INTO payment_proofs (
                payment_id, order_id, file_path, original_filename, mime_type, file_size,
                utr_number, uploaded_by_customer_id, verification_action
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'submitted')
            """,
            (
                pay["id"],
                order_id,
                rel_path,
                orig_name,
                mime_type,
                file_size,
                (utr_number or "").strip(),
                customer_id,
            ),
        )
        conn.execute(
            "UPDATE orders SET status = 'Payment Verification Pending', updated_at = datetime('now') WHERE id = ?",
            (order_id,),
        )
        conn.execute(
            """
            INSERT INTO order_status_history (order_id, status, note, updated_by_type, updated_by_id, updated_by_name)
            VALUES (?, 'Payment Verification Pending', ?, 'customer', ?, ?)
            """,
            (
                order_id,
                f"Payment proof uploaded (UTR: {utr_number or 'N/A'}). Pending admin review.",
                customer_id,
                order["customer_name"],
            ),
        )


def _commit_or_restore_stock_for_order(conn, order_row, target_status: str, actor_id: int | None) -> None:
    items = conn.execute("SELECT * FROM order_items WHERE order_id = ?", (order_row["id"],)).fetchall()
    if target_status in ("Shipped", "Out for Delivery", "Delivered") and not order_row["stock_deducted"]:
        for it in items:
            if it["is_pre_order_token"]:
                continue
            qty = int(it["quantity"])
            inv = conn.execute("SELECT stock_qty, reserved_qty FROM inventory WHERE product_id = ?", (it["product_id"],)).fetchone()
            if inv:
                new_stock = max(0, int(inv["stock_qty"]) - qty)
                new_res = max(0, int(inv["reserved_qty"]) - qty)
                conn.execute(
                    "UPDATE inventory SET stock_qty = ?, reserved_qty = ?, updated_at = datetime('now') WHERE product_id = ?",
                    (new_stock, new_res, it["product_id"]),
                )
                conn.execute(
                    """
                    INSERT INTO inventory_history (
                        product_id, change_qty, previous_qty, new_qty, change_type,
                        reference_type, reference_id, note, actor_type, actor_id
                    ) VALUES (?, ?, ?, ?, 'order_commit', 'order', ?, ?, 'admin', ?)
                    """,
                    (
                        it["product_id"],
                        -qty,
                        int(inv["stock_qty"]),
                        new_stock,
                        order_row["order_number"],
                        f"Dispatched {qty} unit(s) for {order_row['order_number']}",
                        actor_id,
                    ),
                )
        conn.execute("UPDATE orders SET stock_deducted = 1 WHERE id = ?", (order_row["id"],))

    elif target_status in ("Cancelled", "Refunded") and not order_row["stock_restored"]:
        for it in items:
            qty = int(it["quantity"])
            if it["is_pre_order_token"]:
                conn.execute(
                    """
                    UPDATE products
                    SET pre_order_reserved_count = MAX(0, pre_order_reserved_count - ?),
                        updated_at = datetime('now')
                    WHERE id = ?
                    """,
                    (qty, it["product_id"]),
                )
                continue
            inv = conn.execute("SELECT stock_qty, reserved_qty FROM inventory WHERE product_id = ?", (it["product_id"],)).fetchone()
            if inv:
                if order_row["stock_deducted"]:
                    new_stock = int(inv["stock_qty"]) + qty
                    conn.execute(
                        "UPDATE inventory SET stock_qty = ?, updated_at = datetime('now') WHERE product_id = ?",
                        (new_stock, it["product_id"]),
                    )
                    conn.execute(
                        """
                        INSERT INTO inventory_history (
                            product_id, change_qty, previous_qty, new_qty, change_type,
                            reference_type, reference_id, note, actor_type, actor_id
                        ) VALUES (?, ?, ?, ?, 'cancellation_restore', 'order', ?, ?, 'admin', ?)
                        """,
                        (
                            it["product_id"],
                            qty,
                            int(inv["stock_qty"]),
                            new_stock,
                            order_row["order_number"],
                            f"Restored {qty} unit(s) from cancelled order {order_row['order_number']}",
                            actor_id,
                        ),
                    )
                else:
                    new_res = max(0, int(inv["reserved_qty"]) - qty)
                    conn.execute(
                        "UPDATE inventory SET reserved_qty = ?, updated_at = datetime('now') WHERE product_id = ?",
                        (new_res, it["product_id"]),
                    )
                    avail_prev = int(inv["stock_qty"]) - int(inv["reserved_qty"])
                    avail_new = int(inv["stock_qty"]) - new_res
                    conn.execute(
                        """
                        INSERT INTO inventory_history (
                            product_id, change_qty, previous_qty, new_qty, change_type,
                            reference_type, reference_id, note, actor_type, actor_id
                        ) VALUES (?, ?, ?, ?, 'order_release', 'order', ?, ?, 'admin', ?)
                        """,
                        (
                            it["product_id"],
                            qty,
                            avail_prev,
                            avail_new,
                            order_row["order_number"],
                            f"Released reservation of {qty} unit(s) for cancelled order {order_row['order_number']}",
                            actor_id,
                        ),
                    )
        conn.execute("UPDATE orders SET stock_restored = 1 WHERE id = ?", (order_row["id"],))
        conn.execute(
            "UPDATE garage_holds SET hold_status = 'cancelled', updated_at = datetime('now') WHERE order_id = ? AND hold_status IN ('pending_payment', 'active')",
            (order_row["id"],),
        )
        conn.execute(
            "UPDATE pre_orders SET status = ?, updated_at = datetime('now') WHERE order_id = ?",
            ("Refunded" if target_status == "Refunded" else "Cancelled", order_row["id"]),
        )


def review_payment(
    *,
    payment_id: int,
    decision: str,
    admin_user: dict,
    note: str = "",
    cancel_on_reject: bool = False,
) -> dict:
    if decision not in ("approve", "reject"):
        raise ValueError("Decision must be 'approve' or 'reject'.")
    settings = get_store_settings()
    hold_days = get_int_setting(settings, "garage_hold_days", 60)

    with transaction() as conn:
        pay = conn.execute("SELECT * FROM payments WHERE id = ?", (payment_id,)).fetchone()
        if not pay:
            raise ValueError("Payment not found.")
        order = conn.execute("SELECT * FROM orders WHERE id = ?", (pay["order_id"],)).fetchone()
        if not order:
            raise ValueError("Order not found.")
        if order["status"] in ("Cancelled", "Refunded", "Delivered"):
            raise ValueError(f"Order #{order['order_number']} is {order['status']} and cannot be updated.")
        if pay["status"] == "Verified":
            raise ValueError("Payment is already verified.")

        latest_proof = conn.execute(
            "SELECT * FROM payment_proofs WHERE payment_id = ? ORDER BY id DESC LIMIT 1",
            (payment_id,),
        ).fetchone()

        if decision == "approve":
            conn.execute(
                """
                UPDATE payments
                SET status = 'Verified', verified_by_admin_id = ?, verified_at = datetime('now'),
                    admin_notes = ?, updated_at = datetime('now')
                WHERE id = ?
                """,
                (admin_user["id"], note, payment_id),
            )
            if latest_proof:
                conn.execute(
                    """
                    INSERT INTO payment_proofs (
                        payment_id, order_id, file_path, original_filename, mime_type, file_size,
                        utr_number, uploaded_by_customer_id, verification_action,
                        reviewed_by_admin_id, review_note, reviewed_at
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'approved', ?, ?, datetime('now'))
                    """,
                    (
                        payment_id,
                        order["id"],
                        latest_proof["file_path"],
                        latest_proof["original_filename"],
                        latest_proof["mime_type"],
                        latest_proof["file_size"],
                        pay["utr_number"],
                        latest_proof["uploaded_by_customer_id"],
                        admin_user["id"],
                        note or "Payment verified by admin",
                    ),
                )
            conn.execute(
                "UPDATE orders SET status = 'Payment Verified', updated_at = datetime('now') WHERE id = ?",
                (order["id"],),
            )
            conn.execute(
                """
                INSERT INTO order_status_history (
                    order_id, status, note, updated_by_type, updated_by_id, updated_by_name
                ) VALUES (?, 'Payment Verified', ?, 'admin', ?, ?)
                """,
                (
                    order["id"],
                    note or "UPI payment verified by admin.",
                    admin_user["id"],
                    admin_user["full_name"],
                ),
            )

            # Activate Garage Holds if any
            holds = conn.execute(
                "SELECT id FROM garage_holds WHERE order_id = ? AND hold_status = 'pending_payment'",
                (order["id"],),
            ).fetchall()
            for h in holds:
                conn.execute(
                    """
                    UPDATE garage_holds
                    SET hold_status = 'active',
                        hold_started_at = datetime('now'),
                        expires_at = datetime('now', '+' || ? || ' days'),
                        updated_at = datetime('now')
                    WHERE id = ?
                    """,
                    (hold_days, h["id"]),
                )
                conn.execute(
                    """
                    INSERT INTO garage_hold_history (garage_hold_id, action, note, actor_type, actor_id)
                    VALUES (?, 'activated', ?, 'admin', ?)
                    """,
                    (h["id"], f"Activated {hold_days}-day Garage Hold after payment verification.", admin_user["id"]),
                )

            # Update pre-orders if any
            conn.execute(
                "UPDATE pre_orders SET status = 'Token Verified', updated_at = datetime('now') WHERE order_id = ? AND status = 'Pending Token Payment'",
                (order["id"],),
            )
            log_admin_action(conn, admin_user, "payment_approved", "payment", payment_id, {"order_number": order["order_number"], "note": note})
            return {"status": "Verified", "order_status": "Payment Verified"}

        else:
            conn.execute(
                """
                UPDATE payments
                SET status = 'Rejected', verified_by_admin_id = ?, verified_at = datetime('now'),
                    admin_notes = ?, updated_at = datetime('now')
                WHERE id = ?
                """,
                (admin_user["id"], note, payment_id),
            )
            if latest_proof:
                conn.execute(
                    """
                    INSERT INTO payment_proofs (
                        payment_id, order_id, file_path, original_filename, mime_type, file_size,
                        utr_number, uploaded_by_customer_id, verification_action,
                        reviewed_by_admin_id, review_note, reviewed_at
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'rejected', ?, ?, datetime('now'))
                    """,
                    (
                        payment_id,
                        order["id"],
                        latest_proof["file_path"],
                        latest_proof["original_filename"],
                        latest_proof["mime_type"],
                        latest_proof["file_size"],
                        pay["utr_number"],
                        latest_proof["uploaded_by_customer_id"],
                        admin_user["id"],
                        note or "Payment proof rejected",
                    ),
                )
            new_order_status = "Cancelled" if cancel_on_reject else "Pending Payment"
            conn.execute(
                "UPDATE orders SET status = ?, updated_at = datetime('now') WHERE id = ?",
                (new_order_status, order["id"]),
            )
            conn.execute(
                """
                INSERT INTO order_status_history (
                    order_id, status, note, updated_by_type, updated_by_id, updated_by_name
                ) VALUES (?, ?, ?, 'admin', ?, ?)
                """,
                (
                    order["id"],
                    new_order_status,
                    f"Payment rejected: {note or 'Invalid or unmatched proof.'}",
                    admin_user["id"],
                    admin_user["full_name"],
                ),
            )
            if cancel_on_reject:
                _commit_or_restore_stock_for_order(conn, order, "Cancelled", admin_user["id"])
            log_admin_action(conn, admin_user, "payment_rejected", "payment", payment_id, {"order_number": order["order_number"], "note": note, "cancelled": cancel_on_reject})
            return {"status": "Rejected", "order_status": new_order_status}


def update_order_status(
    *,
    order_id: int,
    new_status: str,
    admin_user: dict,
    note: str = "",
    courier_name: str = "",
    tracking_number: str = "",
    tracking_url: str = "",
    shipping_date: str = "",
    delivered_date: str = "",
    dispatch_notes: str = "",
) -> None:
    if new_status not in ORDER_STATUSES:
        raise ValueError("Invalid order status.")

    with transaction() as conn:
        order = conn.execute("SELECT * FROM orders WHERE id = ?", (order_id,)).fetchone()
        if not order:
            raise ValueError("Order not found.")

        current_status = order["status"]
        if current_status == "Delivered":
            raise ValueError(
                "Order is already Delivered. Status cannot be reverted or updated unless the customer submits a return/refund request."
            )
        if current_status in ("Cancelled", "Refunded"):
            raise ValueError(f"Order is {current_status} and cannot be modified.")

        allowed = ALLOWED_ADMIN_TRANSITIONS.get(current_status, [])
        if new_status != current_status and new_status not in allowed:
            raise ValueError(
                f"Invalid status transition from '{current_status}' to '{new_status}'."
            )

        if (
            (order["fulfillment_mode"] or "") == "garage_hold"
            and new_status in GARAGE_LOCKED_DISPATCH_STATUSES
            and not order_garage_dispatch_allowed(conn, order)
        ):
            raise ValueError(
                "Garage Hold order: Admin can only update status up to 'Packed' until the customer requests dispatch from their Collector Garage."
            )

        conn.execute(
            "UPDATE orders SET status = ?, updated_at = datetime('now') WHERE id = ?",
            (new_status, order_id),
        )
        conn.execute(
            """
            INSERT INTO order_status_history (
                order_id, status, note, updated_by_type, updated_by_id, updated_by_name
            ) VALUES (?, ?, ?, 'admin', ?, ?)
            """,
            (
                order_id,
                new_status,
                note or f"Status updated to {new_status}",
                admin_user["id"],
                admin_user["full_name"],
            ),
        )

        # Update shipping details if any provided or status is shipped/delivered
        ship = conn.execute("SELECT * FROM shipping WHERE order_id = ?", (order_id,)).fetchone()
        if ship:
            c_name = courier_name.strip() if courier_name.strip() else ship["courier_name"]
            t_num = tracking_number.strip() if tracking_number.strip() else ship["tracking_number"]
            t_url = tracking_url.strip() if tracking_url.strip() else ship["tracking_url"]
            s_date = shipping_date.strip() if shipping_date.strip() else (
                datetime.now(timezone.utc).strftime("%Y-%m-%d") if new_status == "Shipped" and not ship["shipping_date"] else ship["shipping_date"]
            )
            d_date = delivered_date.strip() if delivered_date.strip() else (
                datetime.now(timezone.utc).strftime("%Y-%m-%d") if new_status == "Delivered" and not ship["delivered_date"] else ship["delivered_date"]
            )
            d_notes = dispatch_notes.strip() if dispatch_notes.strip() else ship["dispatch_notes"]
            conn.execute(
                """
                UPDATE shipping
                SET courier_name = ?, tracking_number = ?, tracking_url = ?,
                    shipping_date = ?, delivered_date = ?, dispatch_notes = ?,
                    updated_by_admin_id = ?, updated_at = datetime('now')
                WHERE order_id = ?
                """,
                (c_name, t_num, t_url, s_date, d_date, d_notes, admin_user["id"], order_id),
            )

        _commit_or_restore_stock_for_order(conn, order, new_status, admin_user["id"])
        log_admin_action(
            conn,
            admin_user,
            "order_status_updated",
            "order",
            order_id,
            {"order_number": order["order_number"], "new_status": new_status, "note": note},
        )


def submit_customer_return_request(
    *,
    order_id: int,
    customer_id: int | None,
    actor_name: str,
    reason: str,
) -> None:
    clean_reason = (reason or "").strip()
    if len(clean_reason) < 5:
        raise ValueError("Please provide a brief reason for your return/refund request (at least 5 characters).")

    with transaction() as conn:
        order = conn.execute("SELECT * FROM orders WHERE id = ?", (order_id,)).fetchone()
        if not order:
            raise ValueError("Order not found.")
        if order["status"] != "Delivered":
            raise ValueError("Return/refund requests can only be submitted for Delivered orders.")

        conn.execute(
            "UPDATE orders SET status = 'Refund Requested', updated_at = datetime('now') WHERE id = ?",
            (order_id,),
        )
        conn.execute(
            """
            INSERT INTO order_status_history (
                order_id, status, note, updated_by_type, updated_by_id, updated_by_name
            ) VALUES (?, 'Refund Requested', ?, 'customer', ?, ?)
            """,
            (
                order_id,
                f"Customer return/refund request: {clean_reason}",
                customer_id,
                actor_name or order["customer_name"],
            ),
        )


def get_order_full_details(order_id: int) -> dict | None:
    db = get_db()
    order = db.execute("SELECT * FROM orders WHERE id = ?", (order_id,)).fetchone()
    if not order:
        return None
    d = dict(order)
    d["shipping_address"] = parse_json_safe(d.get("shipping_address_json"), {})
    d["billing_address"] = parse_json_safe(d.get("billing_address_json"), {})
    d["shipping_rule_snapshot"] = parse_json_safe(d.get("shipping_rule_snapshot_json"), {})
    d["subtotal_formatted"] = format_inr(d["subtotal_paise"])
    d["discount_formatted"] = format_inr(d["discount_paise"])
    d["shipping_formatted"] = format_inr(d["shipping_paise"])
    d["total_formatted"] = format_inr(d["total_paise"])

    items = db.execute("SELECT * FROM order_items WHERE order_id = ?", (order_id,)).fetchall()
    d["items"] = []
    for it in items:
        itd = dict(it)
        itd["unit_price_formatted"] = format_inr(itd["unit_price_paise"])
        itd["line_total_formatted"] = format_inr(itd["line_total_paise"])
        itd["balance_due_formatted"] = format_inr(itd["balance_due_paise"])
        d["items"].append(itd)

    payment = db.execute("SELECT * FROM payments WHERE order_id = ? ORDER BY id DESC LIMIT 1", (order_id,)).fetchone()
    d["payment"] = dict(payment) if payment else None
    if d["payment"]:
        d["payment"]["amount_formatted"] = format_inr(d["payment"]["amount_paise"])

    proofs = db.execute(
        """
        SELECT pp.*, au.full_name AS reviewer_name
        FROM payment_proofs pp
        LEFT JOIN admin_users au ON au.id = pp.reviewed_by_admin_id
        WHERE pp.order_id = ?
        ORDER BY pp.id DESC
        """,
        (order_id,),
    ).fetchall()
    d["payment_proofs"] = [dict(p) for p in proofs]

    ship = db.execute("SELECT * FROM shipping WHERE order_id = ?", (order_id,)).fetchone()
    d["shipping"] = dict(ship) if ship else None

    history = db.execute(
        "SELECT * FROM order_status_history WHERE order_id = ? ORDER BY id ASC",
        (order_id,),
    ).fetchall()
    d["history"] = [dict(h) for h in history]
    return d
