CREATE TABLE clinic_discount_rules (
 id INTEGER PRIMARY KEY AUTOINCREMENT, clinic_contact_id INTEGER NOT NULL,
 discount_group TEXT NOT NULL, label TEXT NOT NULL, percent REAL NOT NULL DEFAULT 0 CHECK(percent BETWEEN 0 AND 100),
 UNIQUE(clinic_contact_id,discount_group), FOREIGN KEY(clinic_contact_id) REFERENCES directory_contacts(id) ON DELETE CASCADE
);
CREATE TABLE clinic_tariffs (
 id INTEGER PRIMARY KEY AUTOINCREMENT, clinic_contact_id INTEGER NOT NULL, label TEXT NOT NULL COLLATE NOCASE,
 category TEXT NOT NULL DEFAULT 'other', discount_group TEXT NOT NULL DEFAULT 'act', unit_label TEXT NOT NULL DEFAULT 'acte',
 medication_id INTEGER, vaccine_id INTEGER, dewormer_id INTEGER, amount_cents INTEGER NOT NULL CHECK(amount_cents>=0),
 active INTEGER NOT NULL DEFAULT 1 CHECK(active IN(0,1)), notes TEXT, created_at TEXT NOT NULL DEFAULT(datetime('now')), updated_at TEXT NOT NULL DEFAULT(datetime('now')),
 FOREIGN KEY(clinic_contact_id) REFERENCES directory_contacts(id) ON DELETE CASCADE,
 FOREIGN KEY(medication_id) REFERENCES ref_medications(id) ON DELETE SET NULL,
 FOREIGN KEY(vaccine_id) REFERENCES ref_vaccines(id) ON DELETE SET NULL,
 FOREIGN KEY(dewormer_id) REFERENCES ref_dewormers(id) ON DELETE SET NULL, UNIQUE(clinic_contact_id,label)
);
CREATE INDEX idx_clinic_tariffs_clinic ON clinic_tariffs(clinic_contact_id,active,label);
CREATE TABLE animal_expenses (
 id INTEGER PRIMARY KEY AUTOINCREMENT, animal_id INTEGER NOT NULL, clinic_contact_id INTEGER, tariff_id INTEGER,
 source_type TEXT, source_id INTEGER, label TEXT NOT NULL, occurred_on TEXT NOT NULL, quantity REAL NOT NULL DEFAULT 1 CHECK(quantity>0),
 catalog_unit_cents INTEGER NOT NULL CHECK(catalog_unit_cents>=0), discount_percent REAL NOT NULL DEFAULT 0,
 total_cents INTEGER NOT NULL CHECK(total_cents>=0), notes TEXT, created_by INTEGER, created_at TEXT NOT NULL DEFAULT(datetime('now')),
 FOREIGN KEY(animal_id) REFERENCES animals(id) ON DELETE CASCADE, FOREIGN KEY(clinic_contact_id) REFERENCES directory_contacts(id) ON DELETE SET NULL,
 FOREIGN KEY(tariff_id) REFERENCES clinic_tariffs(id) ON DELETE SET NULL, FOREIGN KEY(created_by) REFERENCES users(id) ON DELETE SET NULL
);
CREATE INDEX idx_animal_expenses_animal_date ON animal_expenses(animal_id,occurred_on);
