CREATE TABLE animal_location_history (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  animal_id INTEGER NOT NULL,
  from_status TEXT,
  from_refuge_room TEXT,
  from_care_box_key TEXT,
  from_address TEXT,
  to_status TEXT,
  to_refuge_room TEXT,
  to_care_box_key TEXT,
  to_address TEXT,
  reason TEXT,
  source TEXT NOT NULL DEFAULT 'animal_form',
  moved_at TEXT NOT NULL DEFAULT (datetime('now')),
  user_id INTEGER,
  FOREIGN KEY(animal_id) REFERENCES animals(id) ON DELETE CASCADE,
  FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE SET NULL
);

CREATE INDEX idx_animal_location_history_animal_date
  ON animal_location_history(animal_id, moved_at DESC, id DESC);

-- Les animaux déjà présents commencent avec un état de référence. Il ne s'agit
-- pas d'un déplacement inventé, mais du point de départ de leur future chronologie.
INSERT INTO animal_location_history (
  animal_id, to_status, to_refuge_room, to_care_box_key, to_address,
  reason, source, moved_at
)
SELECT id, status, refuge_room, care_box_key, current_address,
       'État initial lors de l’activation de l’historique', 'migration',
       datetime('now')
FROM animals;
