-- Level-local achievements and normalized document reveal requirements.
-- Requirements live on boards so they clone with immutable template versions;
-- earned/seen state lives on the mutable level instance.

ALTER TABLE osint.levels
  ADD CONSTRAINT levels_id_board_unique UNIQUE (id,board_id);

CREATE TABLE osint.level_flags (
  level_id UUID NOT NULL,
  board_id UUID NOT NULL,
  flag_key TEXT NOT NULL CHECK (flag_key ~ '^[a-z][a-z0-9_.-]{0,63}$'),
  earned_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  PRIMARY KEY (level_id,flag_key),
  FOREIGN KEY (level_id,board_id) REFERENCES osint.levels(id,board_id) ON DELETE CASCADE
);
CREATE INDEX level_flags_board_idx ON osint.level_flags (board_id,flag_key);

CREATE TABLE osint.document_flag_requirements (
  board_id UUID NOT NULL REFERENCES osint.boards(id) ON DELETE CASCADE,
  document_exhibit_id UUID NOT NULL REFERENCES osint.document_exhibits(exhibit_id) ON DELETE CASCADE,
  flag_key TEXT NOT NULL CHECK (flag_key ~ '^[a-z][a-z0-9_.-]{0,63}$'),
  PRIMARY KEY (document_exhibit_id,flag_key),
  FOREIGN KEY (board_id,document_exhibit_id) REFERENCES osint.exhibits(board_id,id) ON DELETE CASCADE
);
CREATE INDEX document_flag_requirements_board_idx ON osint.document_flag_requirements (board_id,flag_key);

CREATE TABLE osint.level_seen_documents (
  level_id UUID NOT NULL,
  board_id UUID NOT NULL,
  document_exhibit_id UUID NOT NULL REFERENCES osint.document_exhibits(exhibit_id) ON DELETE CASCADE,
  seen_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  PRIMARY KEY (level_id,document_exhibit_id),
  FOREIGN KEY (level_id,board_id) REFERENCES osint.levels(id,board_id) ON DELETE CASCADE,
  FOREIGN KEY (board_id,document_exhibit_id) REFERENCES osint.exhibits(board_id,id) ON DELETE CASCADE
);

COMMENT ON TABLE osint.level_flags IS 'Boolean achievements earned within one mutable level instance.';
COMMENT ON TABLE osint.document_flag_requirements IS 'All listed flags must be earned before a document is included in the play-mode level payload.';
COMMENT ON TABLE osint.level_seen_documents IS 'Documents whose first-arrival animation has already been acknowledged for this level.';
