-- Data-defined level success conditions. Goals and their requirements belong to
-- clonable boards; completion is derived from the mutable level's existing flags.

CREATE TABLE osint.level_goals (
  id UUID PRIMARY KEY,
  board_id UUID NOT NULL REFERENCES osint.boards(id) ON DELETE CASCADE,
  origin_goal_id UUID REFERENCES osint.level_goals(id) ON DELETE SET NULL,
  goal_key TEXT NOT NULL CHECK (goal_key ~ '^[a-z][a-z0-9_.-]{0,63}$'),
  title TEXT NOT NULL CHECK (char_length(btrim(title)) BETWEEN 1 AND 200),
  instructions TEXT NOT NULL DEFAULT '',
  completion_message TEXT NOT NULL DEFAULT '',
  enabled BOOLEAN NOT NULL DEFAULT TRUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  UNIQUE (board_id,id),
  UNIQUE (board_id,goal_key)
);
CREATE INDEX level_goals_board_enabled_idx ON osint.level_goals (board_id,created_at,id) WHERE enabled;

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

COMMENT ON TABLE osint.level_goals IS 'Clonable, authored player objectives. Completion is derived from required flags on a mutable level.';
COMMENT ON TABLE osint.level_goal_flag_requirements IS 'All listed level flags must be earned for the owning goal to be complete.';
