-- Saved-template store for the PDF report exporter.
--
-- Each row holds a named, port-scoped report configuration that
-- admins / sales-managers can save once and reps re-run with a
-- single click ("Monthly board report", "Weekly pipeline review",
-- etc.). The `config` JSONB matches the discriminated-union shape
-- the route schema enforces, so the same `kind` + `widgetIds` /
-- `columns` / `filters` keys round-trip cleanly.
--
-- Apply in dev:
--   PGPASSWORD=changeme psql -h localhost -p 5434 -U crm \
--     -d port_nimara_crm -f src/lib/db/migrations/0079_report_templates.sql

CREATE TABLE IF NOT EXISTS report_templates (
  id                text PRIMARY KEY,
  port_id           text NOT NULL REFERENCES ports(id) ON DELETE CASCADE,
  kind              text NOT NULL,
  name              text NOT NULL,
  description       text,
  config            jsonb NOT NULL,
  created_by        text NOT NULL,
  created_at        timestamptz NOT NULL DEFAULT NOW(),
  updated_at        timestamptz NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_report_templates_port
  ON report_templates (port_id);

CREATE INDEX IF NOT EXISTS idx_report_templates_port_kind
  ON report_templates (port_id, kind);

-- Sibling-name uniqueness within a port + kind so reps don't end up
-- with two "Monthly board report" templates of the same kind.
CREATE UNIQUE INDEX IF NOT EXISTS uniq_report_templates_port_kind_name
  ON report_templates (port_id, kind, LOWER(name));
