PRAGMA foreign_keys = ON;

ALTER TABLE animals ADD COLUMN care_box_key TEXT;
ALTER TABLE treatments ADD COLUMN give_morning INTEGER NOT NULL DEFAULT 0;
ALTER TABLE treatments ADD COLUMN give_evening INTEGER NOT NULL DEFAULT 0;
ALTER TABLE treatments ADD COLUMN give_as_needed INTEGER NOT NULL DEFAULT 0;

CREATE TABLE IF NOT EXISTS care_room_layouts (
  room TEXT PRIMARY KEY CHECK(room IN ('care','quarantine')),
  top_layout TEXT NOT NULL DEFAULT 'split' CHECK(top_layout IN ('split','merged')),
  bottom_layout TEXT NOT NULL DEFAULT 'split' CHECK(bottom_layout IN ('split','left2','right2','merged')),
  updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
INSERT OR IGNORE INTO care_room_layouts(room) VALUES('care'),('quarantine');

CREATE TABLE IF NOT EXISTS care_rounds (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  round_date TEXT NOT NULL,
  period TEXT NOT NULL CHECK(period IN ('morning','evening')),
  performed_by TEXT,
  started_at TEXT NOT NULL DEFAULT (datetime('now')),
  completed_at TEXT,
  UNIQUE(round_date, period)
);

CREATE TABLE IF NOT EXISTS care_round_observations (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  round_id INTEGER NOT NULL,
  animal_id INTEGER NOT NULL,
  food TEXT NOT NULL DEFAULT 'normal' CHECK(food IN ('normal','little','refused')),
  water TEXT NOT NULL DEFAULT 'normal' CHECK(water IN ('normal','renewed','abnormal')),
  urine TEXT NOT NULL DEFAULT 'normal' CHECK(urine IN ('normal','absent','abnormal')),
  stool TEXT NOT NULL DEFAULT 'normal' CHECK(stool IN ('normal','absent','abnormal')),
  general_state TEXT NOT NULL DEFAULT 'good' CHECK(general_state IN ('good','watch','alert')),
  comment TEXT,
  checked_at TEXT NOT NULL DEFAULT (datetime('now')),
  UNIQUE(round_id, animal_id),
  FOREIGN KEY(round_id) REFERENCES care_rounds(id) ON DELETE CASCADE,
  FOREIGN KEY(animal_id) REFERENCES animals(id) ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS treatment_administrations (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  round_id INTEGER NOT NULL,
  treatment_id INTEGER NOT NULL,
  animal_id INTEGER NOT NULL,
  status TEXT NOT NULL CHECK(status IN ('given','skipped')),
  comment TEXT,
  administered_at TEXT NOT NULL DEFAULT (datetime('now')),
  UNIQUE(round_id, treatment_id),
  FOREIGN KEY(round_id) REFERENCES care_rounds(id) ON DELETE CASCADE,
  FOREIGN KEY(treatment_id) REFERENCES treatments(id) ON DELETE CASCADE,
  FOREIGN KEY(animal_id) REFERENCES animals(id) ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS idx_care_observations_round ON care_round_observations(round_id);
CREATE INDEX IF NOT EXISTS idx_treatment_admin_round ON treatment_administrations(round_id);
