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

const dbPath = process.env.DB_PATH || path.join(__dirname, 'data/school.db');
const db = new Database(dbPath);
db.pragma('foreign_keys = ON');

console.log('Seeding library data into school.db...');

try {
  // Clear any existing mock library data (optional, but counts are already 0)
  db.prepare('DELETE FROM library_fines').run();
  db.prepare('DELETE FROM library_reservations').run();
  db.prepare('DELETE FROM library_issues').run();

  // Reset book available copies to total copies before starting
  const books = db.prepare('SELECT id, total_copies FROM library_books').all();
  for (const b of books) {
    db.prepare('UPDATE library_books SET available_copies = ? WHERE id = ?').run(b.total_copies, b.id);
  }

  // Define student/librarian IDs found in users table
  const studentIds = [3, 23, 24, 25, 26]; // Nyasha Mapfumo, Kudzai Makoni, Tafadzwa Khumalo, Simbarashe Moyo, Shingai Muzenda
  const librarianId = 5; // Tawanda Sibanda

  // Define issue data
  // Current local time: 2026-06-21
  const issuesToSeed = [
    {
      uid: uuidv4(),
      book_id: 1, // Things Fall Apart
      user_id: 3, // Nyasha Mapfumo
      issue_date: '2026-06-01',
      due_date: '2026-06-15',
      return_date: '2026-06-14',
      status: 'returned',
      issued_by: librarianId
    },
    {
      uid: uuidv4(),
      book_id: 2, // Cry, the Beloved Country
      user_id: 23, // Kudzai Makoni
      issue_date: '2026-06-05',
      due_date: '2026-06-19', // Overdue (due before June 21)
      return_date: null,
      status: 'issued',
      issued_by: librarianId
    },
    {
      uid: uuidv4(),
      book_id: 3, // Nervous Conditions
      user_id: 24, // Tafadzwa Khumalo
      issue_date: '2026-06-15',
      due_date: '2026-06-29', // Active (due after June 21)
      return_date: null,
      status: 'issued',
      issued_by: librarianId
    },
    {
      uid: uuidv4(),
      book_id: 4, // House of Hunger
      user_id: 25, // Simbarashe Moyo
      issue_date: '2026-06-10',
      due_date: '2026-06-24', // Active
      return_date: null,
      status: 'issued',
      issued_by: librarianId
    },
    {
      uid: uuidv4(),
      book_id: 1, // Things Fall Apart
      user_id: 26, // Shingai Muzenda
      issue_date: '2026-06-02',
      due_date: '2026-06-16', // Overdue
      return_date: null,
      status: 'issued',
      issued_by: librarianId
    }
  ];

  const insertIssue = db.prepare(`
    INSERT INTO library_issues (uid, book_id, user_id, issue_date, due_date, return_date, status, issued_by)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
  `);

  const issueIds = [];
  for (const issue of issuesToSeed) {
    const res = insertIssue.run(
      issue.uid,
      issue.book_id,
      issue.user_id,
      issue.issue_date,
      issue.due_date,
      issue.return_date,
      issue.status,
      issue.issued_by
    );
    issueIds.push({ id: res.lastInsertRowid, book_id: issue.book_id, status: issue.status });
    
    // Decrement available copies if it is active (issued)
    if (issue.status === 'issued') {
      db.prepare('UPDATE library_books SET available_copies = available_copies - 1 WHERE id = ?').run(issue.book_id);
    }
  }

  console.log(`Successfully seeded ${issuesToSeed.length} issues.`);

  // Define fines
  const finesToSeed = [
    {
      uid: uuidv4(),
      issue_id: issueIds[1].id, // Issue 2 (Kudzai Makoni - Overdue)
      user_id: 23,
      amount: 5.00,
      reason: 'Late return penalty for Cry, the Beloved Country',
      status: 'unpaid'
    },
    {
      uid: uuidv4(),
      issue_id: issueIds[4].id, // Issue 5 (Shingai Muzenda - Overdue)
      user_id: 26,
      amount: 2.50,
      reason: 'Late return penalty for Things Fall Apart',
      status: 'unpaid'
    },
    {
      uid: uuidv4(),
      issue_id: issueIds[0].id, // Issue 1 (Nyasha Mapfumo - Returned)
      user_id: 3,
      amount: 1.50,
      reason: 'Minor cover scratch penalty',
      status: 'paid'
    }
  ];

  const insertFine = db.prepare(`
    INSERT INTO library_fines (uid, issue_id, user_id, amount, reason, status)
    VALUES (?, ?, ?, ?, ?, ?)
  `);

  for (const fine of finesToSeed) {
    insertFine.run(
      fine.uid,
      fine.issue_id,
      fine.user_id,
      fine.amount,
      fine.reason,
      fine.status
    );
  }

  console.log(`Successfully seeded ${finesToSeed.length} fines.`);

  // Define reservations
  const reservationsToSeed = [
    {
      uid: uuidv4(),
      book_id: 1, // Things Fall Apart
      user_id: 23, // Kudzai Makoni
      reservation_date: '2026-06-20',
      status: 'pending',
      notes: 'Need for Literature assignment next week'
    },
    {
      uid: uuidv4(),
      book_id: 3, // Nervous Conditions
      user_id: 25, // Simbarashe Moyo
      reservation_date: '2026-06-21',
      status: 'pending',
      notes: 'Prep study'
    },
    {
      uid: uuidv4(),
      book_id: 4, // House of Hunger
      user_id: 24, // Tafadzwa Khumalo
      reservation_date: '2026-06-18',
      status: 'fulfilled',
      notes: 'Class research request'
    }
  ];

  const insertReservation = db.prepare(`
    INSERT INTO library_reservations (uid, book_id, user_id, reservation_date, status, notes)
    VALUES (?, ?, ?, ?, ?, ?)
  `);

  for (const res of reservationsToSeed) {
    insertReservation.run(
      res.uid,
      res.book_id,
      res.user_id,
      res.reservation_date,
      res.status,
      res.notes
    );
  }

  console.log(`Successfully seeded ${reservationsToSeed.length} reservations.`);
  console.log('Library database seeding complete!');

} catch (err) {
  console.error('Failed to seed library database:', err);
}
