// seedSurveyData.js - Script to add sample survey data to project databases
import sequelize from './config/config.js';
import Treelogy from './models/treelogy.js';
import { getProjectConnection, createProjectDatabase } from './utils/dbManager.js';
import { createSurveyModel } from './models/survey.js';

// Sample survey data
const sampleSurveys = [
  {
    tree_name: 'Banyan Tree',
    local_name: 'Bargad',
    other_name: 'Ficus benghalensis',
    latitude: 19.0760,
    longitude: 72.8777,
    tree_height: 25.5,
    tree_girth: 8.2,
    tree_age: 45,
    tree_condition: 'HEALTHY',
    tree_ownership: 'PUBLIC',
    economic_importance: 'HIGH',
    remarks: 'Large heritage tree with extensive canopy',
    species_type: 'BANYAN',
    is_heritage: true,
    is_rare: false,
    is_indigenous: true,
    is_exotic: false,
    host_plants: 'Epiphytic ferns, orchids',
    images: ['tree1.jpg', 'tree1_canopy.jpg'],
    user_id: 1,
    client_id: 1,
    treelogy_id: 1,
    survey_date: new Date('2024-01-15'),
    entered_time: new Date('2024-01-15T10:30:00'),
    status: 'ACTIVE',
    verified: true,
    verified_by: 1,
    verified_at: new Date('2024-01-16T09:00:00')
  },
  {
    tree_name: 'Neem Tree',
    local_name: 'Neem',
    other_name: 'Azadirachta indica',
    latitude: 19.0765,
    longitude: 72.8782,
    tree_height: 18.0,
    tree_girth: 3.5,
    tree_age: 25,
    tree_condition: 'HEALTHY',
    tree_ownership: 'PRIVATE',
    economic_importance: 'MEDIUM',
    remarks: 'Well-maintained tree with medicinal properties',
    species_type: 'NEEM',
    is_heritage: false,
    is_rare: false,
    is_indigenous: true,
    is_exotic: false,
    host_plants: 'None',
    images: ['tree2.jpg'],
    user_id: 2,
    client_id: 1,
    treelogy_id: 1,
    survey_date: new Date('2024-01-16'),
    entered_time: new Date('2024-01-16T14:20:00'),
    status: 'ACTIVE',
    verified: true,
    verified_by: 1,
    verified_at: new Date('2024-01-17T08:30:00')
  },
  {
    tree_name: 'Mango Tree',
    local_name: 'Aam',
    other_name: 'Mangifera indica',
    latitude: 19.0770,
    longitude: 72.8787,
    tree_height: 22.0,
    tree_girth: 5.8,
    tree_age: 35,
    tree_condition: 'HEALTHY',
    tree_ownership: 'PRIVATE',
    economic_importance: 'HIGH',
    remarks: 'Fruit-bearing tree, well cared for',
    species_type: 'MANGO',
    is_heritage: false,
    is_rare: false,
    is_indigenous: true,
    is_exotic: false,
    host_plants: 'None',
    images: ['tree3.jpg', 'tree3_fruits.jpg'],
    user_id: 3,
    client_id: 1,
    treelogy_id: 1,
    survey_date: new Date('2024-01-17'),
    entered_time: new Date('2024-01-17T11:45:00'),
    status: 'ACTIVE',
    verified: false,
    verified_by: null,
    verified_at: null
  },
  {
    tree_name: 'Eucalyptus',
    local_name: 'Nilgiri',
    other_name: 'Eucalyptus globulus',
    latitude: 19.0762,
    longitude: 72.8779,
    tree_height: 30.0,
    tree_girth: 6.5,
    tree_age: 20,
    tree_condition: 'HEALTHY',
    tree_ownership: 'PUBLIC',
    economic_importance: 'MEDIUM',
    remarks: 'Fast-growing exotic species',
    species_type: 'EUCALYPTUS',
    is_heritage: false,
    is_rare: false,
    is_indigenous: false,
    is_exotic: true,
    host_plants: 'None',
    images: ['tree4.jpg'],
    user_id: 1,
    client_id: 1,
    treelogy_id: 1,
    survey_date: new Date('2024-01-18'),
    entered_time: new Date('2024-01-18T16:10:00'),
    status: 'ACTIVE',
    verified: true,
    verified_by: 1,
    verified_at: new Date('2024-01-19T10:15:00')
  },
  {
    tree_name: 'Peepal Tree',
    local_name: 'Peepal',
    other_name: 'Ficus religiosa',
    latitude: 19.0768,
    longitude: 72.8785,
    tree_height: 20.0,
    tree_girth: 4.2,
    tree_age: 30,
    tree_condition: 'HEALTHY',
    tree_ownership: 'PUBLIC',
    economic_importance: 'HIGH',
    remarks: 'Sacred tree with religious significance',
    species_type: 'PEEPAL',
    is_heritage: true,
    is_rare: false,
    is_indigenous: true,
    is_exotic: false,
    host_plants: 'None',
    images: ['tree5.jpg'],
    user_id: 2,
    client_id: 1,
    treelogy_id: 1,
    survey_date: new Date('2024-01-19'),
    entered_time: new Date('2024-01-19T13:30:00'),
    status: 'ACTIVE',
    verified: true,
    verified_by: 1,
    verified_at: new Date('2024-01-20T09:45:00')
  }
];

// Additional surveys for different projects
const techCorpSurveys = [
  {
    tree_name: 'Oak Tree',
    local_name: 'Oak',
    other_name: 'Quercus robur',
    latitude: 12.9716,
    longitude: 77.5946,
    tree_height: 28.0,
    tree_girth: 7.5,
    tree_age: 40,
    tree_condition: 'HEALTHY',
    tree_ownership: 'PUBLIC',
    economic_importance: 'HIGH',
    remarks: 'Mature oak tree in office complex',
    species_type: 'OAK',
    is_heritage: false,
    is_rare: true,
    is_indigenous: false,
    is_exotic: true,
    host_plants: 'Moss, lichens',
    images: ['oak1.jpg'],
    user_id: 4,
    client_id: 2,
    treelogy_id: 3,
    survey_date: new Date('2024-01-20'),
    entered_time: new Date('2024-01-20T10:00:00'),
    status: 'ACTIVE',
    verified: true,
    verified_by: 4,
    verified_at: new Date('2024-01-21T08:00:00')
  },
  {
    tree_name: 'Palm Tree',
    local_name: 'Coconut',
    other_name: 'Cocos nucifera',
    latitude: 12.9720,
    longitude: 77.5950,
    tree_height: 15.0,
    tree_girth: 2.8,
    tree_age: 15,
    tree_condition: 'HEALTHY',
    tree_ownership: 'PRIVATE',
    economic_importance: 'MEDIUM',
    remarks: 'Coconut palm in garden area',
    species_type: 'COCONUT',
    is_heritage: false,
    is_rare: false,
    is_indigenous: true,
    is_exotic: false,
    host_plants: 'None',
    images: ['palm1.jpg'],
    user_id: 5,
    client_id: 2,
    treelogy_id: 3,
    survey_date: new Date('2024-01-21'),
    entered_time: new Date('2024-01-21T14:30:00'),
    status: 'ACTIVE',
    verified: false,
    verified_by: null,
    verified_at: null
  }
];

const urbanBuildersSurveys = [
  {
    tree_name: 'Gulmohar',
    local_name: 'Gulmohar',
    other_name: 'Delonix regia',
    latitude: 28.6139,
    longitude: 77.2090,
    tree_height: 12.0,
    tree_girth: 2.5,
    tree_age: 8,
    tree_condition: 'HEALTHY',
    tree_ownership: 'PUBLIC',
    economic_importance: 'MEDIUM',
    remarks: 'Flowering tree with beautiful red flowers',
    species_type: 'GULMOHAR',
    is_heritage: false,
    is_rare: false,
    is_indigenous: false,
    is_exotic: true,
    host_plants: 'None',
    images: ['gulmohar1.jpg'],
    user_id: 6,
    client_id: 3,
    treelogy_id: 4,
    survey_date: new Date('2024-01-22'),
    entered_time: new Date('2024-01-22T11:15:00'),
    status: 'ACTIVE',
    verified: true,
    verified_by: 6,
    verified_at: new Date('2024-01-23T09:30:00')
  }
];

async function seedSurveyData() {
  try {
    console.log('Starting to seed survey data...');
    
    // Get all projects
    const projects = await Treelogy.findAll({
      where: { status: 'Y' }
    });

    console.log(`Found ${projects.length} projects`);

    for (const project of projects) {
      console.log(`Processing project: ${project.treelogy_name} (${project.dbname})`);
      
      try {
        // Get or create project database connection
        let projectConnection;
        try {
          projectConnection = await getProjectConnection(project.dbname);
        } catch (error) {
          if (error.message.includes('does not exist')) {
            projectConnection = await createProjectDatabase(project.dbname);
          } else {
            throw error;
          }
        }

        // Create survey model for this project
        const Survey = createSurveyModel(projectConnection);

        // Select appropriate survey data based on project
        let surveysToSeed = [];
        if (project.treelogy_name.includes('GreenHeights')) {
          surveysToSeed = sampleSurveys;
        } else if (project.treelogy_name.includes('TechCorp')) {
          surveysToSeed = techCorpSurveys;
        } else if (project.treelogy_name.includes('Urban')) {
          surveysToSeed = urbanBuildersSurveys;
        } else {
          // Default to sample surveys for other projects
          surveysToSeed = sampleSurveys.slice(0, 3);
        }

        // Update treelogy_id in surveys to match current project
        const surveysWithCorrectId = surveysToSeed.map(survey => ({
          ...survey,
          treelogy_id: project.treelogy_id
        }));

        // Create surveys
        const createdSurveys = await Survey.bulkCreate(surveysWithCorrectId);
        console.log(`Created ${createdSurveys.length} surveys for ${project.treelogy_name}`);
        
      } catch (error) {
        console.error(`Error seeding surveys for project ${project.treelogy_name}:`, error);
        // Continue with other projects
      }
    }

    console.log('Survey data seeding completed!');
    
  } catch (error) {
    console.error('Error seeding survey data:', error);
  } finally {
    await sequelize.close();
  }
}

// Run the seed function
seedSurveyData();
