/**
 * Knex migration for Sanatorium & Medical Records enhancements
 * Adds `sanatorium_visits` and `student_immunizations` tables.
 */

exports.up = async function(knex) {
  // 1. sanatorium_visits (Sick bay encounters, vitals, daily clinic logs)
  await knex.schema.raw(`
    CREATE TABLE IF NOT EXISTS sanatorium_visits (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      uid TEXT UNIQUE,
      student_id INTEGER NOT NULL REFERENCES users(id),
      nurse_id INTEGER REFERENCES users(id),
      visit_date DATETIME DEFAULT (datetime('now', 'localtime')),
      chief_complaint TEXT NOT NULL,
      vitals_json TEXT,
      treatment_administered TEXT,
      disposition TEXT DEFAULT 'discharged' CHECK(disposition IN ('discharged', 'admitted', 'sent_home', 'referred_hospital')),
      bed_number INTEGER,
      parent_notified INTEGER DEFAULT 0,
      notes TEXT,
      created_at DATETIME DEFAULT (datetime('now', 'localtime')),
      updated_at DATETIME DEFAULT (datetime('now', 'localtime')),
      last_synced_at DATETIME,
      sync_status TEXT DEFAULT 'pending' CHECK(sync_status IN ('synced', 'pending', 'conflict')),
      is_deleted INTEGER DEFAULT 0
    );
  `);

  // 2. student_immunizations (Vaccination tracking)
  await knex.schema.raw(`
    CREATE TABLE IF NOT EXISTS student_immunizations (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      uid TEXT UNIQUE,
      student_id INTEGER NOT NULL REFERENCES users(id),
      vaccine_name TEXT NOT NULL,
      dose_number INTEGER DEFAULT 1,
      administered_date DATE DEFAULT (date('now', 'localtime')),
      administered_by TEXT,
      batch_number TEXT,
      notes TEXT,
      created_at DATETIME DEFAULT (datetime('now', 'localtime')),
      updated_at DATETIME DEFAULT (datetime('now', 'localtime')),
      last_synced_at DATETIME,
      sync_status TEXT DEFAULT 'pending' CHECK(sync_status IN ('synced', 'pending', 'conflict')),
      is_deleted INTEGER DEFAULT 0
    );
  `);
};

exports.down = async function(knex) {
  await knex.schema.raw('DROP TABLE IF EXISTS student_immunizations;');
  await knex.schema.raw('DROP TABLE IF EXISTS sanatorium_visits;');
};
