CREATE TABLE medical_prescriptions (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  animal_id INTEGER NOT NULL REFERENCES animals(id) ON DELETE CASCADE,
  prescribed_on TEXT NOT NULL,
  veterinarian_contact_id INTEGER REFERENCES directory_contacts(id) ON DELETE SET NULL,
  clinic_contact_id INTEGER REFERENCES directory_contacts(id) ON DELETE SET NULL,
  status TEXT NOT NULL DEFAULT 'active' CHECK(status IN ('active','finished','replaced')),
  notes TEXT,
  original_name TEXT NOT NULL,
  stored_name TEXT NOT NULL,
  mime_type TEXT NOT NULL,
  size_bytes INTEGER NOT NULL DEFAULT 0,
  created_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
  created_at TEXT NOT NULL DEFAULT(datetime('now'))
);
CREATE INDEX idx_prescriptions_animal_date ON medical_prescriptions(animal_id,prescribed_on DESC,id DESC);

CREATE TABLE prescription_treatments (
  prescription_id INTEGER NOT NULL REFERENCES medical_prescriptions(id) ON DELETE CASCADE,
  treatment_id INTEGER NOT NULL REFERENCES treatments(id) ON DELETE CASCADE,
  PRIMARY KEY(prescription_id,treatment_id)
);

CREATE TABLE lab_reports (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  animal_id INTEGER NOT NULL REFERENCES animals(id) ON DELETE CASCADE,
  sampled_on TEXT NOT NULL,
  report_type TEXT,
  laboratory_name TEXT,
  veterinarian_contact_id INTEGER REFERENCES directory_contacts(id) ON DELETE SET NULL,
  clinic_contact_id INTEGER REFERENCES directory_contacts(id) ON DELETE SET NULL,
  notes TEXT,
  original_name TEXT,
  stored_name TEXT,
  mime_type TEXT,
  size_bytes INTEGER NOT NULL DEFAULT 0,
  created_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
  created_at TEXT NOT NULL DEFAULT(datetime('now'))
);
CREATE INDEX idx_lab_reports_animal_date ON lab_reports(animal_id,sampled_on DESC,id DESC);

CREATE TABLE lab_results (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  report_id INTEGER NOT NULL REFERENCES lab_reports(id) ON DELETE CASCADE,
  parameter_name TEXT NOT NULL,
  value REAL NOT NULL,
  unit TEXT,
  reference_min REAL,
  reference_max REAL,
  notes TEXT,
  position INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX idx_lab_results_report ON lab_results(report_id,position,id);
CREATE INDEX idx_lab_results_parameter ON lab_results(parameter_name COLLATE NOCASE);
