-- Marketplace orders (cross-tenant)
-- These tables go in nexus_autoparts (master DB), not tenant DBs

CREATE TABLE IF NOT EXISTS marketplace_orders (
    id SERIAL PRIMARY KEY,
    buyer_tenant_id INTEGER NOT NULL,
    seller_tenant_id INTEGER NOT NULL,
    buyer_name VARCHAR(200),
    seller_name VARCHAR(200),
    total NUMERIC(12,2),
    status VARCHAR(20) DEFAULT 'pending', -- pending, confirmed, shipped, delivered, cancelled
    notes TEXT,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS marketplace_order_items (
    id SERIAL PRIMARY KEY,
    order_id INTEGER REFERENCES marketplace_orders(id),
    part_number VARCHAR(100),
    part_name VARCHAR(300),
    quantity INTEGER,
    unit_price NUMERIC(12,2),
    subtotal NUMERIC(12,2)
);

CREATE INDEX IF NOT EXISTS idx_mp_orders_buyer ON marketplace_orders(buyer_tenant_id);
CREATE INDEX IF NOT EXISTS idx_mp_orders_seller ON marketplace_orders(seller_tenant_id);
CREATE INDEX IF NOT EXISTS idx_mp_orders_status ON marketplace_orders(status);

-- Add is_seller flag to tenants table
ALTER TABLE tenants ADD COLUMN IF NOT EXISTS is_seller BOOLEAN DEFAULT FALSE;
