-- Website contact form submissions (per business)

CREATE TABLE contact_submissions (
  id           BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
  business_id  BIGINT NOT NULL,
  title        VARCHAR(255) NOT NULL,
  name         VARCHAR(255) NOT NULL,
  email        VARCHAR(255),
  cell_number  VARCHAR(20),
  text         TEXT NOT NULL,
  created_at   TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at   TIMESTAMPTZ NOT NULL DEFAULT NOW(),

  CONSTRAINT contact_submissions_business_id_fkey
    FOREIGN KEY (business_id) REFERENCES businesses (id) ON DELETE CASCADE,
  CONSTRAINT contact_submissions_title_nonempty CHECK (char_length(trim(title)) > 0),
  CONSTRAINT contact_submissions_name_nonempty CHECK (char_length(trim(name)) > 0),
  CONSTRAINT contact_submissions_text_nonempty CHECK (char_length(trim(text)) > 0)
);

CREATE INDEX idx_contact_submissions_business_created
  ON contact_submissions (business_id, created_at DESC);

CREATE TRIGGER contact_submissions_set_updated_at
  BEFORE UPDATE ON contact_submissions
  FOR EACH ROW
  EXECUTE FUNCTION set_updated_at();
