-- Phase 4b - email open tracking via a 1×1 pixel endpoint.
-- Adds a per-send open log + cached aggregates on document_sends.

ALTER TABLE "document_sends"
  ADD COLUMN IF NOT EXISTS "track_opens" boolean NOT NULL DEFAULT false,
  ADD COLUMN IF NOT EXISTS "first_opened_at" timestamptz,
  ADD COLUMN IF NOT EXISTS "open_count" integer NOT NULL DEFAULT 0;

CREATE TABLE IF NOT EXISTS "document_send_opens" (
  "id" text PRIMARY KEY,
  "port_id" text NOT NULL REFERENCES "ports"("id"),
  "send_id" text NOT NULL REFERENCES "document_sends"("id") ON DELETE CASCADE,
  "opened_at" timestamptz NOT NULL DEFAULT now(),
  "user_agent" text,
  "referer" text
);

CREATE INDEX IF NOT EXISTS "idx_dso_send" ON "document_send_opens" ("send_id", "opened_at" DESC);
CREATE INDEX IF NOT EXISTS "idx_dso_port" ON "document_send_opens" ("port_id", "opened_at" DESC);
