CREATE EXTENSION IF NOT EXISTS pgcrypto;

-- Messages sent from the Contact page. Each one is also emailed to SUPPORT_EMAIL.
CREATE TABLE contact_messages (
  id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  name        TEXT NOT NULL,
  email       TEXT NOT NULL,
  topic       TEXT NOT NULL,
  app         TEXT,
  message     TEXT NOT NULL,
  status      TEXT NOT NULL DEFAULT 'new' CHECK (status IN ('new', 'answered', 'closed')),
  created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Live chat. A visitor holds a random token for their conversation (kept in
-- their browser), which is how they prove it's theirs without an account.
CREATE TABLE chat_conversations (
  id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  visitor_token   TEXT NOT NULL UNIQUE,
  visitor_name    TEXT NOT NULL,
  visitor_email   TEXT,
  status          TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'closed')),
  last_message_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  created_at      TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE chat_messages (
  id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  conversation_id UUID NOT NULL REFERENCES chat_conversations(id) ON DELETE CASCADE,
  sender          TEXT NOT NULL CHECK (sender IN ('visitor', 'team')),
  body            TEXT NOT NULL,
  created_at      TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX chat_messages_conversation_idx ON chat_messages (conversation_id, created_at);
CREATE INDEX chat_conversations_recent_idx ON chat_conversations (status, last_message_at DESC);
