-- Public enquiries get their own table and lifecycle, separate from bookings.
-- A public submission lands here as `pending`. An admin then either:
--   approve   → status=approved, a booking is created (copy) referencing this
--               enquiry via booking.enquiry_id (admin picks start/end + a client)
--   waitlist  → waitlisted_at set (requires ≥1 date option); stays pending so it
--               can still be approved or declined later
--   declined  → status=declined
--
-- `waitlisted_at` is a parallel timestamp on a pending row, NOT a status — a
-- waitlisted enquiry is still pending and can be approved or declined.
--
-- Dates live in `enquiry_date_option` (1-to-N, priority-ordered), NOT on the
-- enquiry row — a visitor can propose several date ranges in priority order
-- (E6.1). The enquiry has no single start/end of its own; reads that need a
-- "preferred" date pick the lowest-priority option.

CREATE TABLE IF NOT EXISTS enquiry (
  enquiry_id          TEXT PRIMARY KEY,
  venue_id            TEXT NOT NULL REFERENCES venue(venue_id),
  -- Contact details from the public form. No client row exists yet — one is
  -- selected or created on approval.
  contact_name        TEXT,
  contact_email       TEXT NOT NULL,
  contact_phone       TEXT,
  website             TEXT,
  -- Event details.
  event_name          TEXT NOT NULL,
  event_outline       TEXT,
  description         TEXT,
  expected_persons    INTEGER,
  half_house          INTEGER NOT NULL DEFAULT 0,
  notes               TEXT,
  privacy_accepted_at TEXT,
  -- Lifecycle.
  status              TEXT NOT NULL DEFAULT 'pending',  -- pending | approved | declined
  waitlisted_at       TEXT,
  approved_at         TEXT,
  declined_at         TEXT,
  created_at          TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE INDEX IF NOT EXISTS idx_enquiry_venue_status
  ON enquiry (venue_id, status);

-- Prioritized date options for an enquiry (E6.1). `priority` is 0-based; 0 is
-- the visitor's first choice. Optional: an enquiry may have zero options.
CREATE TABLE IF NOT EXISTS enquiry_date_option (
  option_id   TEXT PRIMARY KEY,
  enquiry_id  TEXT NOT NULL REFERENCES enquiry(enquiry_id) ON DELETE CASCADE,
  start_date  TEXT NOT NULL,
  end_date    TEXT NOT NULL,
  priority    INTEGER NOT NULL DEFAULT 0,
  created_at  TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE INDEX IF NOT EXISTS idx_enquiry_date_option_enquiry
  ON enquiry_date_option (enquiry_id, priority);

-- A booking may originate from an approved enquiry. NULL for admin-created
-- bookings. UNIQUE so an enquiry maps to at most one booking (SQLite allows
-- many NULLs in a unique index).
ALTER TABLE booking ADD COLUMN enquiry_id TEXT REFERENCES enquiry(enquiry_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_booking_enquiry
  ON booking (enquiry_id);
