/**
 * Mutare Primary School Seeding Script
 * Run this to seed a realistic Zimbabwean primary school demo environment.
 * Usage: node demo/seed.js
 */

const Database = require('better-sqlite3');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
const bcrypt = require('bcryptjs');

const dbPath = process.env.DB_PATH || path.join(__dirname, '../server/data/school.db');

console.log(`Connecting to database at: ${dbPath}`);
const db = new Database(dbPath);
db.pragma('foreign_keys = ON');

// Helper to create user
const createUser = (email, password, role, firstName, lastName, phone) => {
  const exists = db.prepare('SELECT id FROM users WHERE email = ?').get(email);
  if (exists) {
    db.prepare('DELETE FROM users WHERE id = ?').run(exists.id);
  }
  const hashedPassword = bcrypt.hashSync(password, 10);
  const uid = uuidv4();
  const result = db.prepare(`
    INSERT INTO users (uid, email, password, role, first_name, last_name, phone, sync_status)
    VALUES (?, ?, ?, ?, ?, ?, ?, 'pending')
  `).run(uid, email, hashedPassword, role, firstName, lastName, phone);
  console.log(`Created ${role}: ${email}`);
  return result.lastInsertRowid;
};

db.transaction(() => {
  console.log('Clearing existing demo data...');
  // We clean up specific tables to ensure a clean demo run
  db.prepare("DELETE FROM student_fees").run();
  db.prepare("DELETE FROM enrollments").run();
  db.prepare("DELETE FROM subjects_new").run();
  db.prepare("DELETE FROM classes").run();
  db.prepare("DELETE FROM notices").run();
  db.prepare("DELETE FROM events").run();

  console.log('Seeding school users...');
  
  // Administrators and Staff
  const adminId = createUser('admin@mutareprimary.ac.zw', 'admin123', 'school_admin', 'Thabani', 'Ndlovu', '+263772222222');
  const headId = createUser('headmaster@mutareprimary.ac.zw', 'head123', 'principal', 'Sipho', 'Sibanda', '+263770000003');
  const bursarId = createUser('bursar@mutareprimary.ac.zw', 'bursar123', 'bursar', 'Patience', 'Muzondo', '+263777777777');
  
  // Teachers
  const teacherId1 = createUser('tchirwa@mutareprimary.ac.zw', 'teacher123', 'teacher', 'Chipo', 'Chirwa', '+263773333333');
  const teacherId2 = createUser('tmhaka@mutareprimary.ac.zw', 'teacher123', 'teacher', 'Tawanda', 'Mhaka', '+263773333334');
  
  // Students
  const s1 = createUser('student1@mutareprimary.ac.zw', 'student123', 'student', 'Nyasha', 'Moyo', '+263774444444');
  const s2 = createUser('student2@mutareprimary.ac.zw', 'student123', 'student', 'Tatenda', 'Banda', '+263774444445');
  const s3 = createUser('student3@mutareprimary.ac.zw', 'student123', 'student', 'Kudakwashe', 'Ncube', '+263774444446');
  const s4 = createUser('student4@mutareprimary.ac.zw', 'student123', 'student', 'Rutendo', 'Sithole', '+263774444447');
  
  // Parent
  const parentId = createUser('parent@mutareprimary.ac.zw', 'parent123', 'parent', 'Tendai', 'Moyo', '+263775555555');

  // Link Parent to Students
  db.prepare("DELETE FROM student_parents").run();
  const linkParent = db.prepare(`
    INSERT INTO student_parents (student_id, parent_id) VALUES (?, ?)
  `);
  linkParent.run(s1, parentId);
  linkParent.run(s2, parentId);

  console.log('Seeding primary school classes (Grade 1 to 7)...');
  const insClass = db.prepare(`
    INSERT INTO classes (uid, name, grade_level, class_teacher_id, sync_status)
    VALUES (?, ?, ?, ?, 'pending')
  `);
  
  const g1Id = insClass.run(uuidv4(), 'Grade 1 Gold', 1, teacherId1).lastInsertRowid;
  const g7Id = insClass.run(uuidv4(), 'Grade 7 Purple', 7, teacherId2).lastInsertRowid;

  console.log('Enrolling students...');
  const insEnrollment = db.prepare(`
    INSERT INTO enrollments (uid, student_id, class_id, admission_date, status, sync_status)
    VALUES (?, ?, ?, date('now'), 'active', 'pending')
  `);
  insEnrollment.run(uuidv4(), s1, g7Id);
  insEnrollment.run(uuidv4(), s2, g7Id);
  insEnrollment.run(uuidv4(), s3, g1Id);
  insEnrollment.run(uuidv4(), s4, g1Id);

  console.log('Seeding ZIMSEC Primary school curriculum subjects...');
  const insSubject = db.prepare(`
    INSERT INTO subjects_new (uid, name, code, class_id, teacher_id, sync_status)
    VALUES (?, ?, ?, ?, ?, 'pending')
  `);
  insSubject.run(uuidv4(), 'Mathematics', 'MATH-P7', g7Id, teacherId2);
  insSubject.run(uuidv4(), 'English Language', 'ENG-P7', g7Id, teacherId2);
  insSubject.run(uuidv4(), 'Shona Language', 'SHONA-P7', g7Id, teacherId2);
  insSubject.run(uuidv4(), 'Agriculture & Science', 'SCI-P7', g7Id, teacherId2);
  
  insSubject.run(uuidv4(), 'Numeracy', 'NUM-P1', g1Id, teacherId1);
  insSubject.run(uuidv4(), 'Literacy', 'LIT-P1', g1Id, teacherId1);

  console.log('Seeding realistic student fees and billing...');
  const insFee = db.prepare(`
    INSERT INTO student_fees (uid, student_id, amount, amount_paid, status, academic_year, term, due_date, sync_status)
    VALUES (?, ?, ?, ?, ?, '2026', 'Term 2', date('now', '+30 days'), 'pending')
  `);
  // Tuitions for Mutare Primary School (Grade 7: $250, Grade 1: $200)
  insFee.run(uuidv4(), s1, 250.00, 150.00, 'partial');
  insFee.run(uuidv4(), s2, 250.00, 0.00, 'unpaid');
  insFee.run(uuidv4(), s3, 200.00, 200.00, 'paid');
  insFee.run(uuidv4(), s4, 200.00, 50.00, 'partial');

  console.log('Seeding school notifications...');
  const insNotice = db.prepare(`
    INSERT INTO notices (uid, title, content, category, priority, audience, created_by, sync_status)
    VALUES (?, ?, ?, ?, ?, ?, ?, 'pending')
  `);
  insNotice.run(uuidv4(), 'ZIMSEC Grade 7 Registration Fee Notice', 'Parents are reminded that the ZIMSEC Grade 7 final examination registration fee deadline is next Friday. Please settle at the Bursar office.', 'Administration', 'Urgent', 'Parents', headId);
  insNotice.run(uuidv4(), 'Inter-House Athletic Competitions', 'All students will participate in the track events this Thursday at the main school grounds. House shirts should be worn.', 'Academic', 'Normal', 'All', headId);
  insNotice.run(uuidv4(), 'Sanitation Measures Update', 'The school has installed extra touchless hand washing points across all classroom blocks to support hygienic health measures.', 'Emergency', 'Urgent', 'All', headId);

  console.log('Seeding calendar events...');
  const insEvent = db.prepare(`
    INSERT INTO events (uid, title, description, event_date, event_type, is_public, created_by, sync_status)
    VALUES (?, ?, ?, ?, ?, 1, ?, 'pending')
  `);
  insEvent.run(uuidv4(), 'Term 2 Consultation Day', 'Parents visit class teachers to collect progress report cards and discuss student performance.', '2026-07-25', 'meeting', headId);
  insEvent.run(uuidv4(), 'Grade 7 Mock Examinations Begin', 'Final mock tests in preparation for end-of-year ZIMSEC exams.', '2026-08-03', 'exam', headId);
  insEvent.run(uuidv4(), 'National Heroes Day Holiday', 'School closed for Heroes Day public holiday.', '2026-08-10', 'holiday', headId);
})();

console.log('Seeding completed successfully!');
db.close();
