const Database = require('better-sqlite3');
const path = require('path');
const fs = require('fs');

const DB_DIR = path.join(__dirname, '..', 'database');
const DB_PATH = path.join(DB_DIR, 'gardentrack.db');

// Ensure database directory exists
if (!fs.existsSync(DB_DIR)) {
  fs.mkdirSync(DB_DIR, { recursive: true });
}

let db;
try {
  db = new Database(DB_PATH);
  console.log('Connected to SQLite database');
} catch (err) {
  console.error('Error creating database:', err.message);
  process.exit(1);
}

// Create tables
try {
  // Plants table
  db.exec(`
    CREATE TABLE IF NOT EXISTS plants (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      purchase_location TEXT,
      seedling_age INTEGER,
      type TEXT NOT NULL,
      variety TEXT NOT NULL,
      seedling_height REAL,
      planting_date DATE NOT NULL,
      current_height REAL,
      health_status TEXT DEFAULT 'good' CHECK(health_status IN ('good', 'needs-attention', 'dead')),
      photo_url TEXT,
      current_photo_url TEXT,
      notes TEXT,
      created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
      updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )
  `);

  // Fertilizers table
  db.exec(`
    CREATE TABLE IF NOT EXISTS fertilizers (
       id INTEGER PRIMARY KEY AUTOINCREMENT,
       name TEXT NOT NULL,
       brand TEXT,
       type TEXT NOT NULL CHECK(type IN ('organic', 'synthetic', 'liquid', 'granular', 'slow-release')),
       npk_ratio TEXT,
       description TEXT,
       application_rate TEXT,
       frequency TEXT,
       season TEXT,
       notes TEXT,
       created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
       updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )
  `);

  // Chemicals table
  db.exec(`
    CREATE TABLE IF NOT EXISTS chemicals (
       id INTEGER PRIMARY KEY AUTOINCREMENT,
       name TEXT NOT NULL,
       brand TEXT,
       type TEXT NOT NULL CHECK(type IN ('pesticide', 'herbicide', 'fungicide', 'insecticide', 'miticide')),
       active_ingredient TEXT,
       concentration TEXT,
       target_pests TEXT,
       application_method TEXT,
       safety_period INTEGER,
       notes TEXT,
       created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
       updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )
  `);

  // Plant history table
  db.exec(`
    CREATE TABLE IF NOT EXISTS plant_history (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      plant_id INTEGER NOT NULL,
      year INTEGER NOT NULL,
      blooming_date DATE,
      fruiting_date DATE,
      created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
      updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
      FOREIGN KEY (plant_id) REFERENCES plants (id) ON DELETE CASCADE
    )
  `);

  // Harvest records table
  db.exec(`
    CREATE TABLE IF NOT EXISTS harvest_records (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      plant_id INTEGER NOT NULL,
      date DATE NOT NULL,
      quantity REAL NOT NULL,
      unit TEXT NOT NULL,
      notes TEXT,
      created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
      updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
      FOREIGN KEY (plant_id) REFERENCES plants (id) ON DELETE CASCADE
    )
  `);

  db.exec(`
    CREATE TABLE IF NOT EXISTS maintenance_records (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      plant_id INTEGER NOT NULL,
      date DATE NOT NULL,
      type TEXT NOT NULL CHECK(type IN ('chemical', 'fertilizer', 'watering', 'pruning', 'transplanting', 'other')),
      description TEXT NOT NULL,
      amount TEXT,
      fertilizer_id INTEGER,
      chemical_id INTEGER,
      created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
      updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
      FOREIGN KEY (plant_id) REFERENCES plants (id) ON DELETE CASCADE,
      FOREIGN KEY (fertilizer_id) REFERENCES fertilizers (id) ON DELETE SET NULL,
      FOREIGN KEY (chemical_id) REFERENCES chemicals (id) ON DELETE SET NULL
    )
  `);

  // Tasks table
  db.exec(`
    CREATE TABLE IF NOT EXISTS tasks (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      plant_id INTEGER,
      title TEXT NOT NULL,
      description TEXT,
      deadline DATE NOT NULL,
      completed BOOLEAN DEFAULT 0,
      created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
      updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
      FOREIGN KEY (plant_id) REFERENCES plants (id) ON DELETE SET NULL
    )
  `);

  console.log('Database tables created successfully!');

  // Insert sample data
  console.log('Inserting sample data...');

  // Sample fertilizers
  const insertFertilizer = db.prepare(`
    INSERT INTO fertilizers (name, brand, type, npk_ratio, description, application_rate, frequency, season, notes) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
  `);

  insertFertilizer.run('All-Purpose Garden Fertilizer', 'Miracle-Gro', 'synthetic', '10-10-10', 'Balanced fertilizer for general garden use', '1 tablespoon per gallon', 'Every 2 weeks', 'Spring-Summer', 'Good for most plants');
  insertFertilizer.run('Organic Compost', 'Local Farm', 'organic', '3-2-2', 'Natural organic matter for soil improvement', '2-3 inches layer', 'Twice yearly', 'Spring-Fall', 'Improves soil structure');
  insertFertilizer.run('Bone Meal', 'Espoma', 'organic', '3-15-0', 'Slow-release phosphorus for root development', '1-2 tablespoons per plant', 'Once per season', 'Spring', 'Great for flowering plants');
  insertFertilizer.run('Liquid Kelp', 'Neptune\'s Harvest', 'liquid', '0-0-1', 'Seaweed extract for plant health', '1 tablespoon per gallon', 'Monthly', 'All seasons', 'Boosts plant immunity');

  // Sample chemicals
  const insertChemical = db.prepare(`
    INSERT INTO chemicals (name, brand, type, active_ingredient, concentration, target_pests, application_method, safety_period, notes) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
  `);

  insertChemical.run('Neem Oil', 'Garden Safe', 'insecticide', 'Azadirachtin', '0.9%', 'Aphids, whiteflies, spider mites', 'Foliar spray', 1, 'Organic option, safe for beneficial insects');
  insertChemical.run('Copper Fungicide', 'Bonide', 'fungicide', 'Copper sulfate', '8%', 'Blight, rust, mildew', 'Foliar spray', 7, 'Use in early morning or evening');
  insertChemical.run('Bt Spray', 'Safer Brand', 'pesticide', 'Bacillus thuringiensis', '0.5%', 'Caterpillars, larvae', 'Foliar spray', 0, 'Organic, targets specific pests');
  insertChemical.run('Systemic Insecticide', 'Bayer', 'insecticide', 'Imidacloprid', '1.47%', 'Aphids, scale, thrips', 'Soil drench', 21, 'Long-lasting protection');

  // Sample plants
  const insertPlant = db.prepare(`
    INSERT INTO plants (purchase_location, seedling_age, type, variety, seedling_height, planting_date, current_height, health_status, photo_url, current_photo_url, notes) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `);
  
  insertPlant.run('Local Nursery', 12, 'tree', 'Apple - Honeycrisp', 45.0, '2022-04-15', 180.0, 'good', null, null, 'Growing well, good fruit production');
  insertPlant.run('Garden Center', 8, 'shrub', 'Blueberry - Bluecrop', 25.0, '2023-03-20', 85.0, 'needs-attention', null, null, 'Leaves showing slight discoloration');
  insertPlant.run('Online Store', 3, 'herb', 'Basil - Sweet Genovese', 8.0, '2024-05-10', 35.0, 'good', null, null, 'Producing well, regular harvests');

  // Sample tasks
  const insertTask = db.prepare(`
    INSERT INTO tasks (plant_id, title, description, deadline, completed) 
    VALUES (?, ?, ?, ?, ?)
  `);

  insertTask.run(1, 'fertilizer', 'Apply spring fertilizer', 'Apply all-purpose fertilizer to apple trees for spring growth', '2024-03-15', 0, 1, null);
  insertTask.run(2, 'pruning', 'Prune blueberry bushes', 'Annual pruning before spring growth', '2024-02-28', 1, null, null);
  insertTask.run(3, 'harvesting', 'Harvest basil', 'Regular harvest to encourage growth', '2024-06-01', 0, null, null);
  insertTask.run(1, 'chemical', 'Apply neem oil treatment', 'Preventive neem oil application for pest control', '2024-04-01', 0, null, 1);

  // Sample maintenance records
  const insertMaintenance = db.prepare(`
    INSERT INTO maintenance_records (plant_id, date, type, description, amount, fertilizer_id, chemical_id)
    VALUES (?, ?, ?, ?, ?, ?, ?)
  `);

  insertMaintenance.run(1, '2024-01-10', 'pruning', 'Winter pruning - removed dead branches', null, null, null);
  insertMaintenance.run(2, '2024-01-05', 'fertilizer', 'Applied organic compost', '2 cups', 2, null);
  insertMaintenance.run(3, '2024-05-15', 'watering', 'Deep watering during dry spell', '1 gallon', null, null);
  insertMaintenance.run(1, '2024-03-20', 'chemical', 'Applied neem oil for aphid prevention', '2 tablespoons per gallon', null, 1);

  // Sample harvest records
  const insertHarvest = db.prepare(`
    INSERT INTO harvest_records (plant_id, date, quantity, unit, notes) 
    VALUES (?, ?, ?, ?, ?)
  `);
  
  insertHarvest.run(1, '2023-09-15', 25, 'lbs', 'Excellent harvest, apples were sweet and crisp');
  insertHarvest.run(2, '2023-07-20', 3, 'cups', 'First harvest of the season, berries were plump and sweet');
  insertHarvest.run(3, '2024-05-25', 0.5, 'cups', 'Fresh basil for cooking, very aromatic');

  // Sample observations
  const insertObservation = db.prepare(`
    INSERT INTO plant_observations (plant_id, date, title, observation, weather_conditions, temperature, tags) 
    VALUES (?, ?, ?, ?, ?, ?, ?)
  `);
  
  insertObservation.run(1, '2024-01-15', 'Winter dormancy check', 'Apple tree showing normal winter dormancy. Buds are tight and healthy looking. No signs of pest damage on bark.', 'Clear, cold', 2.5, 'dormancy,health-check,winter');
  insertObservation.run(2, '2024-01-20', 'Pruning completed', 'Finished annual pruning of blueberry bushes. Removed about 20% of old wood and opened up center for better air circulation.', 'Overcast', 8.0, 'pruning,maintenance');
  insertObservation.run(3, '2024-05-12', 'First true leaves', 'Basil seedlings showing first set of true leaves. Growth is vigorous and color is deep green. Ready for transplanting soon.', 'Sunny', 22.0, 'growth,seedling,transplant-ready');

  console.log('Sample data inserted successfully!');
} catch (err) {
  console.error('Error initializing database:', err);
  process.exit(1);
}

db.close();
console.log('Database initialization completed!');