-- Admin-managed document templates: a .docx (stored in MinIO bucket initiative-templates)
-- plus its extracted Jinja placeholder fields. Applicants render a filled PDF by template id.
-- Apply after 014_registration_otp.sql:
--   docker exec -i initiative-postgres psql -U initiative -d initiatives < be0/migrations/015_document_templates.sql

CREATE TABLE IF NOT EXISTS document_templates (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  name TEXT NOT NULL,
  description TEXT,
  storage_key TEXT NOT NULL,
  original_filename TEXT,
  content_sha256 TEXT,
  fields JSONB NOT NULL DEFAULT '[]'::jsonb,
  is_active BOOLEAN NOT NULL DEFAULT TRUE,
  created_by UUID REFERENCES users(id) ON DELETE SET NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_document_templates_active
  ON document_templates (is_active, created_at DESC);

COMMENT ON TABLE document_templates IS
  'Admin-managed DOCX templates (file in MinIO initiative-templates) with extracted Jinja placeholder fields. Applicants render filled PDFs by template id.';
