-- Phase 10: sale listings and bids (enchères)
-- Run after schema.sql (e.g. psql -d builazoo -f server/migrations/001_sale_listings.sql)

CREATE TABLE IF NOT EXISTS sale_listings (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  seller_zoo_id UUID NOT NULL REFERENCES zoos(id) ON DELETE CASCADE,
  animal_id TEXT NOT NULL,
  is_baby BOOLEAN NOT NULL,
  initial_price INTEGER NOT NULL,
  end_at TIMESTAMPTZ NOT NULL,
  status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'sold', 'expired', 'rejected')),
  best_bid_amount INTEGER,
  best_bidder_zoo_id UUID REFERENCES zoos(id) ON DELETE SET NULL,
  sold_at TIMESTAMPTZ,
  reproduction_score_at_sale NUMERIC,
  delivered_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS sale_listings_seller ON sale_listings(seller_zoo_id);
CREATE INDEX IF NOT EXISTS sale_listings_status ON sale_listings(status);
CREATE INDEX IF NOT EXISTS sale_listings_end_at ON sale_listings(end_at);
CREATE INDEX IF NOT EXISTS sale_listings_best_bidder ON sale_listings(best_bidder_zoo_id);

CREATE TABLE IF NOT EXISTS sale_bids (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  listing_id UUID NOT NULL REFERENCES sale_listings(id) ON DELETE CASCADE,
  bidder_zoo_id UUID NOT NULL REFERENCES zoos(id) ON DELETE CASCADE,
  amount INTEGER NOT NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  UNIQUE(listing_id, bidder_zoo_id)
);

CREATE INDEX IF NOT EXISTS sale_bids_listing ON sale_bids(listing_id);
