PRAGMA foreign_keys = ON;

CREATE TABLE IF NOT EXISTS bonded_groups (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  name TEXT,
  notes TEXT,
  active INTEGER NOT NULL DEFAULT 1,
  created_at TEXT NOT NULL DEFAULT (datetime('now')),
  dissolved_at TEXT
);

CREATE TABLE IF NOT EXISTS bonded_group_members (
  group_id INTEGER NOT NULL,
  animal_id INTEGER NOT NULL,
  position INTEGER NOT NULL DEFAULT 1,
  PRIMARY KEY(group_id, animal_id),
  FOREIGN KEY(group_id) REFERENCES bonded_groups(id) ON DELETE CASCADE,
  FOREIGN KEY(animal_id) REFERENCES animals(id) ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS idx_bonded_members_animal
ON bonded_group_members(animal_id);
CREATE INDEX IF NOT EXISTS idx_bonded_members_group ON bonded_group_members(group_id, position);
