-- 0093_website_submissions_inquiry_cols.sql
-- ----------------------------------------------------------------------------
-- Inquiries workbench: tracking + display columns on website_submissions.
--   converted_client_id / converted_interest_id - set when an operator converts
--     an inquiry into CRM entities (FK to clients/interests).
--   contact_name / contact_email - extracted from the JSONB payload at capture
--     time so the list view can search/sort/display via real columns.
--
-- Idempotent: ADD COLUMN IF NOT EXISTS + CREATE INDEX IF NOT EXISTS + a
-- COALESCE backfill that only fills nulls. Safe to re-run.

ALTER TABLE website_submissions
  ADD COLUMN IF NOT EXISTS converted_client_id   text REFERENCES clients(id),
  ADD COLUMN IF NOT EXISTS converted_interest_id text REFERENCES interests(id),
  ADD COLUMN IF NOT EXISTS contact_name  text,
  ADD COLUMN IF NOT EXISTS contact_email text;

CREATE INDEX IF NOT EXISTS idx_ws_contact_email
  ON website_submissions (port_id, contact_email);

-- Backfill display columns from existing payloads (only where still null).
UPDATE website_submissions
SET contact_email = COALESCE(contact_email, NULLIF(payload->>'email', '')),
    contact_name  = COALESCE(
      contact_name,
      NULLIF(TRIM(CONCAT_WS(' ', payload->>'first_name', payload->>'last_name')), ''),
      NULLIF(payload->>'name', ''),
      NULLIF(payload->>'fullName', ''),
      NULLIF(payload->>'full_name', '')
    )
WHERE contact_email IS NULL OR contact_name IS NULL;
