CREATE TABLE animal_placements (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  animal_id INTEGER NOT NULL,
  event_type TEXT NOT NULL CHECK(event_type IN ('reservation','foster','adoption','return','cancellation')),
  event_date TEXT NOT NULL,
  contact_id INTEGER,
  reason TEXT,
  notes TEXT,
  adoption_id INTEGER,
  created_by INTEGER,
  created_at TEXT NOT NULL DEFAULT(datetime('now')),
  FOREIGN KEY(animal_id) REFERENCES animals(id) ON DELETE CASCADE,
  FOREIGN KEY(contact_id) REFERENCES directory_contacts(id) ON DELETE SET NULL,
  FOREIGN KEY(adoption_id) REFERENCES adoptions(id) ON DELETE SET NULL,
  FOREIGN KEY(created_by) REFERENCES users(id) ON DELETE SET NULL
);
CREATE INDEX idx_animal_placements_animal_date ON animal_placements(animal_id,event_date DESC,id DESC);
CREATE UNIQUE INDEX idx_animal_placements_adoption ON animal_placements(adoption_id) WHERE adoption_id IS NOT NULL;

INSERT OR IGNORE INTO animal_placements(animal_id,event_type,event_date,contact_id,reason,notes,adoption_id,created_at)
SELECT animal_id,'adoption',adoption_date,adopter_contact_id,'Adoption définitive',notes,id,COALESCE(created_at,datetime('now')) FROM adoptions;
