ALTER TABLE animal_deaths RENAME TO animal_deaths_before_year_precision;

CREATE TABLE animal_deaths (
  animal_id INTEGER PRIMARY KEY,
  deceased_date TEXT,
  date_precision TEXT NOT NULL DEFAULT 'exact' CHECK(date_precision IN ('exact','approximate','year','unknown')),
  death_age_value INTEGER,
  death_age_unit TEXT CHECK(death_age_unit IN ('day','week','month','year')),
  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,
  memorial_medal_color TEXT CHECK(memorial_medal_color IN ('blue','pink')),
  memorial_medal_count INTEGER NOT NULL DEFAULT 1 CHECK(memorial_medal_count >= 1),
  recovered_source 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')),
  death_year INTEGER CHECK(death_year BETWEEN 1900 AND 2200),
  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
);

INSERT INTO animal_deaths SELECT * FROM animal_deaths_before_year_precision;
DROP TABLE animal_deaths_before_year_precision;
CREATE INDEX idx_animal_deaths_date ON animal_deaths(deceased_date);
CREATE INDEX idx_animal_deaths_year ON animal_deaths(death_year);
CREATE INDEX idx_animal_deaths_cause ON animal_deaths(cause_code,occurred_in_care);
