PRAGMA foreign_keys = ON;

CREATE TABLE IF NOT EXISTS animal_deaths (
  animal_id INTEGER PRIMARY KEY,
  deceased_date TEXT NOT NULL,
  cause_code TEXT NOT NULL,
  cause_details TEXT,
  occurred_in_care INTEGER NOT NULL DEFAULT 1 CHECK(occurred_in_care IN (0,1)),
  place_type TEXT NOT NULL DEFAULT 'refuge' CHECK(place_type IN ('refuge','fa','veterinaire','exterieur','inconnu','autre')),
  place_details TEXT,
  euthanized INTEGER NOT NULL DEFAULT 0 CHECK(euthanized IN (0,1)),
  veterinarian_contact_id INTEGER,
  crematorium_contact_id INTEGER,
  body_disposition TEXT NOT NULL DEFAULT 'pending' CHECK(body_disposition IN ('pending','collective_cremation','individual_cremation','returned_family','burial','other')),
  cremation_date TEXT,
  notes TEXT,
  created_by INTEGER,
  updated_by INTEGER,
  created_at TEXT NOT NULL DEFAULT (datetime('now')),
  updated_at TEXT NOT NULL DEFAULT (datetime('now')),
  FOREIGN KEY(animal_id) REFERENCES animals(id) ON DELETE CASCADE,
  FOREIGN KEY(veterinarian_contact_id) REFERENCES directory_contacts(id) ON DELETE SET NULL,
  FOREIGN KEY(crematorium_contact_id) REFERENCES directory_contacts(id) ON DELETE SET NULL,
  FOREIGN KEY(created_by) REFERENCES users(id) ON DELETE SET NULL,
  FOREIGN KEY(updated_by) REFERENCES users(id) ON DELETE SET NULL
);

CREATE INDEX IF NOT EXISTS idx_animal_deaths_date ON animal_deaths(deceased_date);
CREATE INDEX IF NOT EXISTS idx_animal_deaths_cause ON animal_deaths(cause_code, occurred_in_care);
