-- ============================================================
-- BharathTrucks — Loads & Bids Migration
-- Run in Supabase SQL Editor AFTER app_users migration
-- ============================================================

CREATE TABLE IF NOT EXISTS loads (
  id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
  posted_by UUID NOT NULL REFERENCES app_users(id) ON DELETE CASCADE,
  origin_city TEXT NOT NULL,
  destination_city TEXT NOT NULL,
  weight_tons NUMERIC(5,1) NOT NULL,
  truck_type TEXT NOT NULL,
  material_type TEXT,
  budget NUMERIC(10,2),
  pickup_date DATE NOT NULL,
  description TEXT,
  is_urgent BOOLEAN DEFAULT FALSE,
  status TEXT DEFAULT 'open' CHECK (status IN ('open', 'booked', 'in_transit', 'delivered', 'cancelled')),
  bid_count INTEGER DEFAULT 0,
  accepted_bid_id UUID,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_loads_status ON loads(status);
CREATE INDEX IF NOT EXISTS idx_loads_origin ON loads(origin_city);
CREATE INDEX IF NOT EXISTS idx_loads_destination ON loads(destination_city);
CREATE INDEX IF NOT EXISTS idx_loads_posted_by ON loads(posted_by);
CREATE INDEX IF NOT EXISTS idx_loads_pickup_date ON loads(pickup_date);

CREATE TABLE IF NOT EXISTS bids (
  id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
  load_id UUID NOT NULL REFERENCES loads(id) ON DELETE CASCADE,
  driver_id UUID NOT NULL REFERENCES app_users(id) ON DELETE CASCADE,
  amount NUMERIC(10,2) NOT NULL,
  note TEXT,
  status TEXT DEFAULT 'pending' CHECK (status IN ('pending', 'accepted', 'rejected', 'withdrawn')),
  created_at TIMESTAMPTZ DEFAULT NOW(),
  UNIQUE(load_id, driver_id)
);

CREATE INDEX IF NOT EXISTS idx_bids_load ON bids(load_id);
CREATE INDEX IF NOT EXISTS idx_bids_driver ON bids(driver_id);

-- Auto increment bid_count
CREATE OR REPLACE FUNCTION increment_bid_count()
RETURNS TRIGGER AS $$
BEGIN
  UPDATE loads SET bid_count = bid_count + 1 WHERE id = NEW.load_id;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS bid_count_trigger ON bids;
CREATE TRIGGER bid_count_trigger AFTER INSERT ON bids
  FOR EACH ROW EXECUTE FUNCTION increment_bid_count();

-- updated_at trigger
CREATE OR REPLACE FUNCTION update_updated_at()
RETURNS TRIGGER AS $$
BEGIN NEW.updated_at = NOW(); RETURN NEW; END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS loads_updated_at ON loads;
CREATE TRIGGER loads_updated_at BEFORE UPDATE ON loads
  FOR EACH ROW EXECUTE FUNCTION update_updated_at();

-- RLS
ALTER TABLE loads ENABLE ROW LEVEL SECURITY;
ALTER TABLE bids ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Allow all on loads" ON loads FOR ALL USING (true) WITH CHECK (true);
CREATE POLICY "Allow all on bids" ON bids FOR ALL USING (true) WITH CHECK (true);
