require('dotenv').config();
const bcrypt = require('bcryptjs');
const { sequelize } = require('./config/database');
const { User, Route, Vehicle, Schedule, Setting, Stop, RouteStop, SegmentPrice } = require('./models');

const TRANS_KALAHARI_STOPS = [
  { name: 'Windhoek', country: 'Namibia', is_border: false },
  { name: 'Gobabis', country: 'Namibia', is_border: false },
  { name: 'Buitepos', country: 'Namibia', is_border: true },
  { name: 'Charles Hill', country: 'Botswana', is_border: true },
  { name: 'Tsootsha', country: 'Botswana', is_border: false },
  { name: 'Karakubis', country: 'Botswana', is_border: false },
  { name: 'Ghanzi', country: 'Botswana', is_border: false },
  { name: 'Gaborone', country: 'Botswana', is_border: false },
];

const REQUIRED_ROUTES = [
  { route_code: 'WHK-GAB', origin: 'Windhoek', destination: 'Gaborone', country_origin: 'Namibia', country_destination: 'Botswana', distance_km: 1450, estimated_duration_hours: 18.0 },
  { route_code: 'GAB-WHK', origin: 'Gaborone', destination: 'Windhoek', country_origin: 'Botswana', country_destination: 'Namibia', distance_km: 1450, estimated_duration_hours: 18.0 },
];

const ECONOMY_PRICES_NAD = [
  [0, 350, 400, 450, 500, 550, 650, 1200],
  [0, 0, 150, 200, 250, 300, 400, 950],
  [0, 0, 0, 100, 150, 200, 300, 850],
  [0, 0, 0, 0, 100, 150, 250, 800],
  [0, 0, 0, 0, 0, 100, 150, 700],
  [0, 0, 0, 0, 0, 0, 100, 600],
  [0, 0, 0, 0, 0, 0, 0, 550],
  [0, 0, 0, 0, 0, 0, 0, 0],
];

const ECONOMY_PRICES_BWP = [
  [0, 310, 355, 400, 445, 490, 575, 1060],
  [0, 0, 135, 180, 225, 270, 355, 840],
  [0, 0, 0, 90, 135, 180, 265, 750],
  [0, 0, 0, 0, 90, 135, 220, 705],
  [0, 0, 0, 0, 0, 90, 135, 620],
  [0, 0, 0, 0, 0, 0, 90, 530],
  [0, 0, 0, 0, 0, 0, 0, 485],
  [0, 0, 0, 0, 0, 0, 0, 0],
];

const VIP_PRICES_NAD = [
  [0, 550, 620, 700, 780, 850, 1000, 1850],
  [0, 0, 230, 310, 390, 460, 610, 1460],
  [0, 0, 0, 150, 230, 300, 460, 1310],
  [0, 0, 0, 0, 150, 230, 380, 1230],
  [0, 0, 0, 0, 0, 150, 230, 1080],
  [0, 0, 0, 0, 0, 0, 150, 920],
  [0, 0, 0, 0, 0, 0, 0, 850],
  [0, 0, 0, 0, 0, 0, 0, 0],
];

const VIP_PRICES_BWP = [
  [0, 485, 545, 615, 690, 750, 880, 1630],
  [0, 0, 205, 275, 345, 405, 540, 1290],
  [0, 0, 0, 135, 205, 265, 405, 1155],
  [0, 0, 0, 0, 135, 205, 335, 1085],
  [0, 0, 0, 0, 0, 135, 205, 955],
  [0, 0, 0, 0, 0, 0, 135, 815],
  [0, 0, 0, 0, 0, 0, 0, 750],
  [0, 0, 0, 0, 0, 0, 0, 0],
];

const seed = async () => {
  try {
    await sequelize.sync({ force: false });
    console.log('[Seed] Database synced');

    const adminExists = await User.findOne({ where: { username: 'admin' } });
    if (!adminExists) {
      const hash = await bcrypt.hash('admin123', 10);
      await User.create({
        username: 'admin',
        email: 'admin@tokkie.com',
        password_hash: hash,
        full_name: 'System Admin',
        role: 'admin',
        is_active: true,
      });
      console.log('[Seed] Admin user created (admin@tokkie.com / admin123)');

      await User.create({
        username: 'manager1',
        email: 'manager@tokkie.com',
        password_hash: hash,
        full_name: 'Operations Manager',
        role: 'manager',
        is_active: true,
      });
      console.log('[Seed] Manager user created (manager@tokkie.com / admin123)');
    }

    for (const stopData of TRANS_KALAHARI_STOPS) {
      await Stop.findOrCreate({
        where: { name: stopData.name },
        defaults: stopData,
      });
    }
    const stopCount = await Stop.count();
    console.log(`[Seed] ${stopCount} stops ready`);

    for (const routeData of REQUIRED_ROUTES) {
      await Route.findOrCreate({
        where: { route_code: routeData.route_code },
        defaults: routeData,
      });
    }
    const routeCount = await Route.count();
    console.log(`[Seed] ${routeCount} routes ready (${REQUIRED_ROUTES.length} required)`);

    const allStops = await Stop.findAll({ order: [['id', 'ASC']] });
    const whkGabRoute = await Route.findOne({ where: { route_code: 'WHK-GAB' } });
    const gabWhkRoute = await Route.findOne({ where: { route_code: 'GAB-WHK' } });

    for (const [route, direction] of [[whkGabRoute, 'fwd'], [gabWhkRoute, 'rev']]) {
      if (!route) continue;
      const existing = await RouteStop.count({ where: { route_id: route.id } });
      if (existing === 0) {
        const items = allStops.map((stop, index) => ({
          route_id: route.id,
          stop_id: stop.id,
          order: direction === 'rev' ? allStops.length - index : index + 1,
        }));
        await RouteStop.bulkCreate(items);
        console.log(`[Seed] ${items.length} route_stops created for ${route.route_code}`);
      } else {
        console.log(`[Seed] ${existing} route_stops already exist for ${route.route_code}`);
      }
    }

    for (const route of [whkGabRoute, gabWhkRoute]) {
      if (!route) continue;
      const existingPrices = await SegmentPrice.count({ where: { route_id: route.id } });
      if (existingPrices === 0) {
        const stopCount = allStops.length;
        const segmentPrices = [];
        for (let from = 0; from < stopCount; from++) {
          for (let to = from + 1; to < stopCount; to++) {
            segmentPrices.push({
              route_id: route.id,
              from_stop_id: allStops[from].id,
              to_stop_id: allStops[to].id,
              vehicle_type: 'economy',
              price_nad: ECONOMY_PRICES_NAD[from][to],
              price_bwp: ECONOMY_PRICES_BWP[from][to],
            });
            segmentPrices.push({
              route_id: route.id,
              from_stop_id: allStops[from].id,
              to_stop_id: allStops[to].id,
              vehicle_type: 'vip',
              price_nad: VIP_PRICES_NAD[from][to],
              price_bwp: VIP_PRICES_BWP[from][to],
            });
          }
        }
        await SegmentPrice.bulkCreate(segmentPrices);
        console.log(`[Seed] ${segmentPrices.length} segment prices created for ${route.route_code}`);
      } else {
        console.log(`[Seed] ${existingPrices} segment prices already exist for ${route.route_code}`);
      }
    }

    const vehiclesExist = await Vehicle.count();
    if (vehiclesExist === 0) {
      await Vehicle.bulkCreate([
        { vehicle_code: 'QUANTUM-1', vehicle_type: 'economy', vehicle_name: 'Toyota Quantum', capacity: 15, has_trailer: true, has_ac: true },
        { vehicle_code: 'PREMACY-1', vehicle_type: 'vip', vehicle_name: 'Mazda Premacy', capacity: 4, has_trailer: false, has_ac: true },
      ]);
      console.log('[Seed] Vehicles created');
    }

    const schedulesExist = await Schedule.count();
    if (schedulesExist === 0) {
      const vehicles = await Vehicle.findAll();
      const quantum = vehicles.find((v) => v.vehicle_code === 'QUANTUM-1');
      const premacy = vehicles.find((v) => v.vehicle_code === 'PREMACY-1');

      const schedulesData = [];
      if (whkGabRoute) {
        schedulesData.push(
          { route_id: whkGabRoute.id, vehicle_id: quantum.id, departure_day: 'Friday', departure_time: '05:00:00', arrival_time: '23:00:00', price_per_seat: 1200.00, currency: 'NAD', notes: 'Economy Shuttle: 15-seater, luggage trailer included, zero hidden bag fees' },
          { route_id: whkGabRoute.id, vehicle_id: premacy.id, departure_day: 'Friday', departure_time: '06:30:00', arrival_time: '00:30:00', price_per_seat: 1850.00, currency: 'NAD', notes: 'VIP Express: Door-to-door, 4-seater Premacy, fast-track border clearance' },
        );
      }
      if (gabWhkRoute) {
        schedulesData.push(
          { route_id: gabWhkRoute.id, vehicle_id: quantum.id, departure_day: 'Sunday', departure_time: '05:00:00', arrival_time: '23:00:00', price_per_seat: 1060.00, currency: 'BWP', notes: 'Economy Shuttle: 15-seater, luggage trailer included, zero hidden bag fees' },
          { route_id: gabWhkRoute.id, vehicle_id: premacy.id, departure_day: 'Sunday', departure_time: '06:30:00', arrival_time: '00:30:00', price_per_seat: 1630.00, currency: 'BWP', notes: 'VIP Express: Door-to-door, 4-seater Premacy, fast-track border clearance' },
        );
      }
      await Schedule.bulkCreate(schedulesData);
      console.log(`[Seed] ${schedulesData.length} schedules created`);
    } else {
      console.log('[Seed] Schedules already exist');
    }

    const settingsExist = await Setting.count();
    if (settingsExist === 0) {
      await Setting.bulkCreate([
        { setting_key: 'booking_cutoff_day', setting_value: 'Wednesday', setting_group: 'booking', description: 'Last day to book for Friday departure' },
        { setting_key: 'booking_cutoff_time', setting_value: '17:00', setting_group: 'booking', description: 'Cutoff time on booking cutoff day' },
        { setting_key: 'deposit_percentage', setting_value: '50', setting_group: 'payment', description: 'Deposit percentage' },
        { setting_key: 'currency', setting_value: 'NAD', setting_group: 'general', description: 'Default currency' },
        { setting_key: 'currency_secondary', setting_value: 'BWP', setting_group: 'general', description: 'Secondary currency for Botswana routes' },
        { setting_key: 'whatsapp_number', setting_value: '+264811275285', setting_group: 'contact', description: 'WhatsApp number' },
        { setting_key: 'phone_number', setting_value: '+264811275285', setting_group: 'contact', description: 'Phone number' },
        { setting_key: 'support_email', setting_value: 'tokkiebookings@shuttlesnamibia.com', setting_group: 'contact', description: 'Support email' },
        { setting_key: 'cancellation_policy', setting_value: 'Cancellations must be made 24 hours before departure', setting_group: 'general', description: 'Cancellation policy' },
      ]);
      console.log('[Seed] Settings created');
    }

    console.log('[Seed] Complete!');
    process.exit(0);
  } catch (error) {
    console.error('[Seed] Error:', error.message);
    process.exit(1);
  }
};

seed();
