-- ============================================================
-- Migration 004: Bidding & Negotiation System
-- ============================================================

-- Bids table for freight offers
CREATE TABLE bids (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    load_id TEXT REFERENCES loads(id) ON DELETE CASCADE,
    driver_id TEXT REFERENCES portal_users(id) ON DELETE CASCADE,
    bid_amount NUMERIC(12,2) NOT NULL,
    notes TEXT,
    status TEXT DEFAULT 'pending' CHECK (status IN ('pending', 'accepted', 'rejected', 'counter_offer')),
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Indexes for fast lookup of bids per load
CREATE INDEX idx_bids_load_id ON bids(load_id);
CREATE INDEX idx_bids_driver_id ON bids(driver_id);
CREATE INDEX idx_bids_status ON bids(status);

-- ============================================================
-- Audit triggers for Bids
-- ============================================================
CREATE TRIGGER trg_bids_updated_at BEFORE UPDATE ON bids
    FOR EACH ROW EXECUTE FUNCTION update_updated_at();
