import { Database } from 'sqlite3';
import path from 'path';

const dbPath = path.join(__dirname, '..', '..', 'data', 'app.db');
const db = new Database(dbPath);

// Helper to run a query with parameters and return a promise
const run = (sql: string, params: any[] = []): Promise<void> => {
  return new Promise((resolve, reject) => {
    db.run(sql, params, function (err) {
      if (err) reject(err);
      else resolve();
    });
  });
};

// Helper to get a single row
const get = <T>(sql: string, params: any[] = []): Promise<T | undefined> => {
  return new Promise((resolve, reject) => {
    db.get(sql, params, (err, row) => {
      if (err) reject(err);
      else resolve(row as T | undefined);
    });
  });
};

async function insertMockData() {
  try {
    await run('PRAGMA foreign_keys = ON');

    // Insert iPads
    const iPads = [
      { asset_tag: 'IPAD001', model: 'iPad Pro 12.9' },
      { asset_tag: 'IPAD002', model: 'iPad Air' },
      { asset_tag: 'IPAD003', model: 'iPad Mini' },
    ];

    const iPadIds: number[] = [];
    for (const ipad of iPads) {
      await run(
        'INSERT OR IGNORE INTO iPads (asset_tag, model, is_mock) VALUES (?, ?, 1)',
        [ipad.asset_tag, ipad.model]
      );
      const row = await get<{ id: number }>('SELECT id FROM iPads WHERE asset_tag = ?', [ipad.asset_tag]);
      if (row) iPadIds.push(row.id);
    }

    // Insert repairs
    const repairs = [
      { i_pad_id: iPadIds[0], repair_type: 'Broken screen', cost: 130.0, repair_date: '2026-01-15' },
      { i_pad_id: iPadIds[0], repair_type: 'Broken charge port', cost: 150.0, repair_date: '2026-01-20' },
      { i_pad_id: iPadIds[1], repair_type: 'Broken LCD', cost: 130.0, repair_date: '2026-02-01' },
      { i_pad_id: iPadIds[2], repair_type: 'Broken headphone jack', cost: 150.0, repair_date: '2026-02-05' },
      { i_pad_id: iPadIds[2], repair_type: 'Broken volume button', cost: 150.0, repair_date: '2026-02-10' },
    ];

    for (const repair of repairs) {
      await run(
        'INSERT INTO repairs (i_pad_id, repair_type, cost, repair_date, is_mock) VALUES (?, ?, ?, ?, 1)',
        [repair.i_pad_id, repair.repair_type, repair.cost, repair.repair_date]
      );
    }

    console.log('Mock data inserted successfully');
  } catch (err) {
    console.error('Error inserting mock data:', err);
  } finally {
    db.close();
  }
}

insertMockData();
