-- Subscribers-Tabelle mit Double-Opt-In und DSGVO-Consent-Tracking
-- Wird pro Tenant-Schema ausgeführt (SET search_path = tenant_<id>, public vorher)

CREATE TABLE IF NOT EXISTS subscribers (
  id                UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  email             TEXT NOT NULL,
  email_hash        TEXT NOT NULL UNIQUE,
  status            TEXT NOT NULL DEFAULT 'pending'
    CHECK (status IN ('pending', 'active', 'unsubscribed', 'bounced')),
  list_id           UUID,

  -- Double-Opt-In (DSGVO-Pflicht)
  doi_token         TEXT UNIQUE,
  doi_requested_at  TIMESTAMPTZ,
  doi_confirmed_at  TIMESTAMPTZ,

  -- Consent-Nachweis
  consent_ip        INET,
  consent_user_agent TEXT,

  created_at        TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at        TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_subscribers_email_hash ON subscribers(email_hash);
CREATE INDEX IF NOT EXISTS idx_subscribers_doi_token  ON subscribers(doi_token);
CREATE INDEX IF NOT EXISTS idx_subscribers_status     ON subscribers(status);

CREATE OR REPLACE TRIGGER subscribers_updated_at
  BEFORE UPDATE ON subscribers
  FOR EACH ROW EXECUTE FUNCTION update_updated_at();
