-- Shared Postgres schema for Telegram-driven school-work intake.
-- Apply in a dedicated `school_intake` database or adapt to an existing shared DB.

CREATE TABLE IF NOT EXISTS school_paperless_intake (
  intake_id              TEXT PRIMARY KEY,
  class_name             TEXT NOT NULL,
  assignment_name        TEXT NOT NULL,
  submission_kind        TEXT NOT NULL,
  semester               TEXT,
  course_code            TEXT,
  paper_kind             TEXT,
  notes                  TEXT,
  source                 TEXT NOT NULL DEFAULT 'telegram',
  telegram_chat_id       TEXT,
  telegram_message_id    TEXT,
  original_filename      TEXT NOT NULL,
  stored_filename        TEXT NOT NULL,
  mime_type              TEXT NOT NULL,
  file_size_bytes        BIGINT NOT NULL,
  checksum_sha256        TEXT NOT NULL,
  status                 TEXT NOT NULL DEFAULT 'received',
  paperless_task_id      TEXT,
  paperless_document_id  BIGINT,
  paperless_title        TEXT,
  received_at            TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  uploaded_at            TIMESTAMPTZ,
  enriched_at            TIMESTAMPTZ,
  error_text             TEXT,
  created_at             TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at             TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_school_paperless_intake_status ON school_paperless_intake(status);
CREATE INDEX IF NOT EXISTS idx_school_paperless_intake_doc_id ON school_paperless_intake(paperless_document_id);
CREATE INDEX IF NOT EXISTS idx_school_paperless_intake_assignment ON school_paperless_intake(class_name, assignment_name);
CREATE INDEX IF NOT EXISTS idx_school_paperless_intake_checksum ON school_paperless_intake(checksum_sha256);

CREATE TABLE IF NOT EXISTS school_paperless_intake_events (
  id              BIGSERIAL PRIMARY KEY,
  intake_id       TEXT NOT NULL REFERENCES school_paperless_intake(intake_id) ON DELETE CASCADE,
  event_type      TEXT NOT NULL,
  event_payload   JSONB NOT NULL DEFAULT '{}'::jsonb,
  created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_school_paperless_intake_events_intake_id
  ON school_paperless_intake_events(intake_id);
