// seedData.js - Script to add sample data to the database
import sequelize from './config/config.js';
import Client from './models/client.js';
import Treelogy from './models/treelogy.js';
import Login from './models/login.js';
import Mapping from './models/mapping.js';
import DashboardVisibility from './models/dashboardVisibility.js';
import UserMaster from './models/userMaster.js';
import bcrypt from 'bcryptjs';

async function seedData() {
  try {
    console.log('Starting to seed data...');
    
    // Create sample clients
    const clients = await Client.bulkCreate([
      {
        client_name: 'GreenHeights',
        mobile: '9876543210',
        landline: '022-12345678',
        email: 'info@greenheights.com',
        address: '123 Business Park, Mumbai',
        details: 'Real estate development company',
        status: 1
      },
      {
        client_name: 'TechCorp Solutions',
        mobile: '9876543211',
        landline: '022-12345679',
        email: 'contact@techcorp.com',
        address: '456 Tech Hub, Bangalore',
        details: 'Technology consulting firm',
        status: 1
      },
      {
        client_name: 'Urban Builders',
        mobile: '9876543212',
        landline: '022-12345680',
        email: 'hello@urbanbuilders.com',
        address: '789 Construction Zone, Delhi',
        details: 'Construction and infrastructure company',
        status: 1
      }
    ]);

    console.log('Created clients:', clients.length);

    // Create sample projects (treelogies)
    const projects = await Treelogy.bulkCreate([
      {
        treelogy_code: 'GH001',
        treelogy_name: 'GreenHeights Tower A',
        landmark: 'Bandra Kurla Complex',
        dbname: 'greenheights_tower_a',
        client_id: clients[0].id,
        status: 'Y'
      },
      {
        treelogy_code: 'GH002',
        treelogy_name: 'GreenHeights Tower B',
        landmark: 'Andheri West',
        dbname: 'greenheights_tower_b',
        client_id: clients[0].id,
        status: 'Y'
      },
      {
        treelogy_code: 'TC001',
        treelogy_name: 'TechCorp Office Complex',
        landmark: 'Electronic City',
        dbname: 'techcorp_office',
        client_id: clients[1].id,
        status: 'Y'
      },
      {
        treelogy_code: 'UB001',
        treelogy_name: 'Urban Builders Mall',
        landmark: 'Connaught Place',
        dbname: 'urban_mall',
        client_id: clients[2].id,
        status: 'Y'
      }
    ]);

    console.log('Created projects:', projects.length);

    // Get role IDs from UserMaster table
    const superAdminRole = await UserMaster.findOne({ where: { role_name: 'SUPER_ADMIN' } });
    const clientAdminRole = await UserMaster.findOne({ where: { role_name: 'CLIENT_ADMIN' } });
    const projectUserRole = await UserMaster.findOne({ where: { role_name: 'PROJECT_USER' } });
    
    if (!superAdminRole || !clientAdminRole || !projectUserRole) {
      throw new Error('Roles not found. Please run seedUserMaster.js first.');
    }

    // Create sample users
    const hashedPassword = await bcrypt.hash('password123', 10);
    
    const users = await Login.bulkCreate([
      {
        member_id: 'root',
        mobile_number: '9999999999',
        password: hashedPassword,
        name: 'Root Admin',
        role_id: superAdminRole.id,
        client_id: null,
        treelogy_id: null,
        status: 'Y'
      },
      {
        member_id: 'GH001',
        mobile_number: '9876543210',
        password: hashedPassword,
        name: 'GreenHeights Admin',
        role_id: clientAdminRole.id,
        client_id: clients[0].id,
        treelogy_id: projects[0].treelogy_id,
        status: 'Y'
      },
      {
        member_id: 'TC001',
        mobile_number: '9876543211',
        password: hashedPassword,
        name: 'TechCorp Admin',
        role_id: clientAdminRole.id,
        client_id: clients[1].id,
        treelogy_id: projects[2].treelogy_id,
        status: 'Y'
      },
      {
        member_id: 'GHU001',
        mobile_number: '9876543213',
        password: hashedPassword,
        name: 'GreenHeights User',
        role_id: projectUserRole.id,
        client_id: clients[0].id,
        treelogy_id: projects[0].treelogy_id,
        status: 'Y'
      },
      {
        member_id: 'GHU002',
        mobile_number: '9876543214',
        password: hashedPassword,
        name: 'Sarah Johnson',
        role_id: projectUserRole.id,
        client_id: clients[0].id,
        treelogy_id: projects[1].treelogy_id,
        status: 'Y'
      },
      {
        member_id: 'GHU003',
        mobile_number: '9876543215',
        password: hashedPassword,
        name: 'Mike Chen',
        role_id: projectUserRole.id,
        client_id: clients[0].id,
        treelogy_id: projects[0].treelogy_id,
        status: 'Y'
      },
      {
        member_id: 'TCU001',
        mobile_number: '9876543216',
        password: hashedPassword,
        name: 'Alex Rodriguez',
        role_id: projectUserRole.id,
        client_id: clients[1].id,
        treelogy_id: projects[2].treelogy_id,
        status: 'Y'
      },
      {
        member_id: 'TCU002',
        mobile_number: '9876543217',
        password: hashedPassword,
        name: 'Emma Wilson',
        role_id: projectUserRole.id,
        client_id: clients[1].id,
        treelogy_id: projects[3].treelogy_id,
        status: 'Y'
      },
      {
        member_id: 'TCU003',
        mobile_number: '9876543218',
        password: hashedPassword,
        name: 'David Kim',
        role_id: projectUserRole.id,
        client_id: clients[1].id,
        treelogy_id: projects[2].treelogy_id,
        status: 'Y'
      }
    ]);

    console.log('Created users:', users.length);

    // Create mappings for PROJECT_USER level users
    // Find the users by member_id to get correct login_id
    const ghU001 = users.find(u => u.member_id === 'GHU001');
    const ghU002 = users.find(u => u.member_id === 'GHU002');
    const ghU003 = users.find(u => u.member_id === 'GHU003');
    const tcU001 = users.find(u => u.member_id === 'TCU001');
    const tcU002 = users.find(u => u.member_id === 'TCU002');
    const tcU003 = users.find(u => u.member_id === 'TCU003');

    const mappings = await Mapping.bulkCreate([
      {
        login_id: ghU001.login_id, // GHU001
        treelogy_id: projects[0].treelogy_id, // GreenHeights Tower A
        unit_id: 1,
        role: 'RESIDENT',
        view_permission: 'FULL',
        code: 'GHU001-001',
        description: 'GreenHeights Tower A - Unit 1'
      },
      {
        login_id: ghU002.login_id, // GHU002
        treelogy_id: projects[1].treelogy_id, // GreenHeights Tower B
        unit_id: 2,
        role: 'RESIDENT',
        view_permission: 'FULL',
        code: 'GHU002-002',
        description: 'GreenHeights Tower B - Unit 2'
      },
      {
        login_id: ghU003.login_id, // GHU003
        treelogy_id: projects[0].treelogy_id, // GreenHeights Tower A
        unit_id: 3,
        role: 'RESIDENT',
        view_permission: 'FULL',
        code: 'GHU003-003',
        description: 'GreenHeights Tower A - Unit 3'
      },
      {
        login_id: tcU001.login_id, // TCU001
        treelogy_id: projects[2].treelogy_id, // TechCorp Office Complex
        unit_id: 1,
        role: 'EMPLOYEE',
        view_permission: 'FULL',
        code: 'TCU001-001',
        description: 'TechCorp Office - Floor 1'
      },
      {
        login_id: tcU002.login_id, // TCU002
        treelogy_id: projects[3].treelogy_id, // Urban Builders Mall
        unit_id: 1,
        role: 'MANAGER',
        view_permission: 'FULL',
        code: 'TCU002-001',
        description: 'Urban Mall - Shop 1'
      },
      {
        login_id: tcU003.login_id, // TCU003
        treelogy_id: projects[2].treelogy_id, // TechCorp Office Complex
        unit_id: 2,
        role: 'EMPLOYEE',
        view_permission: 'FULL',
        code: 'TCU003-002',
        description: 'TechCorp Office - Floor 2'
      }
    ]);

    console.log('Created mappings:', mappings.length);

    // Initialize dashboard visibility settings for each project
    const dashboardItems = [
      // Statistics Cards (6 cards)
      { card_id: 'total_trees', card_name: 'Total Trees Surveyed', card_type: 'card', is_visible: true, display_order: 1 },
      { card_id: 'qc_completed', card_name: 'QC Completed', card_type: 'card', is_visible: true, display_order: 2 },
      { card_id: 'qc_pending', card_name: 'QC Pending', card_type: 'card', is_visible: true, display_order: 3 },
      { card_id: 'today_entries', card_name: 'Today Entries', card_type: 'card', is_visible: true, display_order: 4 },
      { card_id: 'this_week_entries', card_name: 'This Week Entries', card_type: 'card', is_visible: true, display_order: 5 },
      { card_id: 'this_month_entries', card_name: 'This Month Entries', card_type: 'card', is_visible: true, display_order: 6 },
      
      // Charts (5 charts)
      { card_id: 'condition_chart', card_name: 'Condition wise Donut Chart', card_type: 'chart', is_visible: true, display_order: 7 },
      { card_id: 'remark_chart', card_name: 'Remark wise Tree Count', card_type: 'chart', is_visible: true, display_order: 8 },
      { card_id: 'ownership_chart', card_name: 'Ownership wise Pie Chart', card_type: 'chart', is_visible: true, display_order: 9 },
      { card_id: 'species_chart', card_name: 'Species wise Tree Count (Top 15)', card_type: 'chart', is_visible: true, display_order: 10 },
      { card_id: 'economic_importance_chart', card_name: 'Economic Importance wise Tree Count', card_type: 'chart', is_visible: true, display_order: 11 }
    ];

    // Create dashboard visibility settings for each project
    for (const project of projects) {
      const visibilitySettings = dashboardItems.map(item => ({
        treelogy_id: project.treelogy_id,
        ...item
      }));
      
      await DashboardVisibility.bulkCreate(visibilitySettings);
    }

    console.log('Created dashboard visibility settings for', projects.length, 'projects');
    console.log('Sample data seeded successfully!');
    console.log('\nSample login credentials:');
    console.log('Super Admin: member_id=root, password=password123');
    console.log('GreenHeights Admin: member_id=GH001, password=password123');
    console.log('TechCorp Admin: member_id=TC001, password=password123');
    console.log('\nNormal Users (PROJECT_USER):');
    console.log('GreenHeights User: member_id=GHU001, password=password123');
    console.log('Sarah Johnson: member_id=GHU002, password=password123');
    console.log('Mike Chen: member_id=GHU003, password=password123');
    console.log('Alex Rodriguez: member_id=TCU001, password=password123');
    console.log('Emma Wilson: member_id=TCU002, password=password123');
    console.log('David Kim: member_id=TCU003, password=password123');

  } catch (error) {
    console.error('Error seeding data:', error);
  } finally {
    await sequelize.close();
  }
}

// Run the seed function
seedData();

