UPDATE animal_movements
SET created_at=(SELECT d.deceased_date||' 12:00:00' FROM animal_deaths d WHERE d.animal_id=animal_movements.animal_id),
    place=(SELECT CASE d.place_type WHEN 'refuge' THEN 'Au refuge' WHEN 'fa' THEN 'En famille d''accueil' WHEN 'veterinaire' THEN 'Chez le vétérinaire' WHEN 'exterieur' THEN 'À l''extérieur' WHEN 'inconnu' THEN 'Lieu inconnu' ELSE 'Autre lieu' END FROM animal_deaths d WHERE d.animal_id=animal_movements.animal_id),
    contact_name=(SELECT v.name FROM animal_deaths d LEFT JOIN directory_contacts v ON v.id=d.veterinarian_contact_id WHERE d.animal_id=animal_movements.animal_id),
    note=(SELECT 'Cause : '||CASE d.cause_code WHEN 'disease' THEN 'Maladie' WHEN 'accident' THEN 'Accident' WHEN 'old_age' THEN 'Vieillesse' WHEN 'congenital' THEN 'Malformation ou affection congénitale' WHEN 'surgery_complication' THEN 'Complication médicale ou chirurgicale' WHEN 'poisoning' THEN 'Empoisonnement' WHEN 'unknown' THEN 'Cause inconnue' ELSE 'Autre cause' END||CASE WHEN d.euthanized=1 THEN char(10)||'Euthanasie : oui' ELSE '' END||CASE WHEN c.name IS NOT NULL THEN char(10)||'Crématorium : '||c.name ELSE '' END FROM animal_deaths d LEFT JOIN directory_contacts c ON c.id=d.crematorium_contact_id WHERE d.animal_id=animal_movements.animal_id)
WHERE id IN (
  SELECT MAX(m.id) FROM animal_movements m JOIN animal_deaths d ON d.animal_id=m.animal_id
  WHERE m.kind='exit' AND lower(m.lieu) IN ('décès','deces','décès de l''animal','deces de l''animal') GROUP BY m.animal_id
);
