CREATE TABLE IF NOT EXISTS ref_species (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  code TEXT NOT NULL UNIQUE COLLATE NOCASE,
  name TEXT NOT NULL,
  category TEXT NOT NULL DEFAULT 'autre',
  icon TEXT NOT NULL DEFAULT '🐾',
  color TEXT NOT NULL DEFAULT '#6c757d',
  active INTEGER NOT NULL DEFAULT 1 CHECK(active IN (0,1)),
  sort_order INTEGER NOT NULL DEFAULT 100,
  created_at TEXT NOT NULL DEFAULT (datetime('now')),
  updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE INDEX IF NOT EXISTS idx_ref_species_active_order
ON ref_species(active, sort_order, name);

INSERT OR IGNORE INTO ref_species(code,name,category,icon,color,sort_order) VALUES
('chat','Chat','animaux_compagnie','🐱','#6f8fb3',10),
('chien','Chien','animaux_compagnie','🐶','#b7791f',20),
('lapin','Lapin','nac','🐰','#8b6f47',30),
('furet','Furet','nac','🦦','#7c6651',40),
('cobaye','Cochon d''Inde','nac','🐹','#a06c46',50),
('oiseau','Oiseau','nac','🐦','#3b82a0',60),
('reptile','Reptile','nac','🦎','#56875a',70),
('animal-ferme','Animal de ferme','animal_ferme','🐐','#9a6b3f',80),
('faune-sauvage','Faune sauvage','faune_sauvage','🦅','#496b45',90),
('autre','Autre espèce','autre','🐾','#6c757d',100);

INSERT OR IGNORE INTO ref_species(code,name,category,icon,color,sort_order)
SELECT lower(trim(species)),
       CASE WHEN trim(species)='' THEN 'Espèce inconnue' ELSE upper(substr(trim(species),1,1))||substr(trim(species),2) END,
       'autre','🐾','#6c757d',95
FROM animals
WHERE trim(COALESCE(species,''))<>'';

UPDATE animals SET species='chat' WHERE lower(trim(species))='cat';
UPDATE animals SET species='chien' WHERE lower(trim(species))='dog';
