// =============================================================================
// Seed script for Phase 1 pilot.
// Creates: 1 city (South Mumbai), localities, samuday master, default WhatsApp
// template, and 1 captain user. Run via `pnpm db:seed`.
//
// Idempotent: re-running won't duplicate. Uses upsert by natural keys.
// =============================================================================

import { PrismaClient, LocationType } from '@prisma/client';
import bcrypt from 'bcryptjs';
import * as dotenv from 'dotenv';
import * as path from 'path';

// Load .env from monorepo root
dotenv.config({ path: path.resolve(__dirname, '../../../.env') });

const prisma = new PrismaClient();

const env = (key: string, fallback?: string): string => {
  const v = process.env[key] ?? fallback;
  if (v === undefined) throw new Error(`Missing env var: ${key}`);
  return v;
};

// ---- South Mumbai locality list ----
const SOUTH_MUMBAI_LOCALITIES = [
  'Walkeshwar',
  'Malabar Hill',
  'Marine Lines',
  'Charni Road',
  'Girgaon',
  'Chowpatty',
  'Gamdevi',
  'Khetwadi',
  'Bhuleshwar',
  'Kalbadevi',
  'Zaveri Bazar',
  'Princess Street',
  'Bhendi Bazar',
  'Mandvi',
  'Pydhonie',
  'Dongri',
  'Nagpada',
  'Opera House',
  'Grant Road',
  'Tardeo',
  'Mahalaxmi',
  'Jacob Circle',
  'Mumbai Central',
  'Byculla',
  'Mazgaon',
  'Masjid Bunder',
  'Kalachowky',
  'Parel',
  'Lower Parel',
  'Lalbaug',
];

// ---- Samuday seed list. Captains can add more inline from the vihar form. ----
const SAMUDAY_LIST = [
  'Prem-Bhuvanbhanu Samuday',
  'Sagar Samuday',
];

// ---- Default WhatsApp message template ----
const DEFAULT_WHATSAPP_TEMPLATE = `*|| નમો લોએ સવ્વસાહૂણં ||*
                    🍁
  🙏 *અહો ! શ્રામણ્યમ્* 🙏
                    👣
          🚶🏻‍♂️ *વિહાર* 🚶🏻‍♂️

Day :-  *{{day}}*

Date :- *{{date}}*

Time :- *{{time}}*

Place :- *{{from_name}}*

Dest :- *{{to_name}}*

*{{head_saint}}*
Aadi *{{sadhuji}}* Thana....
Ne Mukva Jawanu Che 👍

🚶 *Vihar Sevaks:*
{{volunteers}}

{{updhi_text}}

📝 {{remarks}}

🔗 {{deep_link}}

  🙏 *Anumodna Varam Var* 🙏
— Vihar Sewa | {{city_name}}`;

// ---- Default volunteer credentials share template ----
const DEFAULT_VOLUNTEER_CREDENTIALS_TEMPLATE = `🙏 *Welcome to Vihar Sewa* 🙏

Hello *{{full_name}}*,

You've been added as a Vihar Sevak for {{city_name}}. Your login credentials:

🔑 *Username:* {{username}}
🔒 *Password:* {{password}}

🔗 *Login here:* {{login_url}}

⚠️ Please change your password after your first login.

For any help, please contact *{{captain_name}}*.

🙏 Anumodna 🙏`;

async function main() {
  console.log('🌱 Seeding Vihar Sewa pilot data...\n');

  // ---- 1. City ----
  const cityName = env('SEED_CITY_NAME', 'South Mumbai');
  const tz = env('SEED_CITY_TIMEZONE', 'Asia/Kolkata');

  const city = await prisma.city.upsert({
    where: { cityId: 1 },
    update: { name: cityName, timezone: tz },
    create: {
      cityId: 1,
      name: cityName,
      state: 'Maharashtra',
      country: 'India',
      timezone: tz,
    },
  });
  console.log(`✓ City: ${city.name} (id=${city.cityId})`);

  // ---- 2. Localities ----
  for (let i = 0; i < SOUTH_MUMBAI_LOCALITIES.length; i++) {
    const name = SOUTH_MUMBAI_LOCALITIES[i]!;
    await prisma.locality.upsert({
      where: { cityId_name: { cityId: city.cityId, name } },
      update: { displayOrder: i },
      create: {
        cityId: city.cityId,
        name,
        displayOrder: i,
      },
    });
  }
  console.log(`✓ ${SOUTH_MUMBAI_LOCALITIES.length} localities seeded`);

  // ---- 3. Samuday master ----
  // Drop any samuday rows not in the desired seed list. Safe in dev where no
  // vihars reference them; will fail if a Vihar still points to a sample row,
  // which is the right behaviour (manual cleanup expected before truncation).
  const removed = await prisma.samuday.deleteMany({
    where: { name: { notIn: SAMUDAY_LIST } },
  });
  if (removed.count > 0) console.log(`✓ Removed ${removed.count} stale samuday row(s)`);
  for (let i = 0; i < SAMUDAY_LIST.length; i++) {
    const name = SAMUDAY_LIST[i]!;
    await prisma.samuday.upsert({
      where: { name },
      update: { displayOrder: i, isActive: true },
      create: { name, displayOrder: i },
    });
  }
  console.log(`✓ ${SAMUDAY_LIST.length} samuday seeded`);

  // ---- 4. City settings ----
  const settings: Record<string, string> = {
    distance_tolerance_km: env('DISTANCE_TOLERANCE_KM', '1.0'),
    auto_close_after_hours: env('AUTO_CLOSE_AFTER_HOURS', '6'),
    route_cache_ttl_days: env('ROUTE_CACHE_TTL_DAYS', '180'),
  };
  for (const [key, value] of Object.entries(settings)) {
    await prisma.citySetting.upsert({
      where: { cityId_key: { cityId: city.cityId, key } },
      update: { value },
      create: { cityId: city.cityId, key, value },
    });
  }
  console.log(`✓ ${Object.keys(settings).length} city settings seeded`);

  // ---- 5. Default WhatsApp template ----
  await prisma.messageTemplate.upsert({
    where: {
      cityId_templateKey: { cityId: city.cityId, templateKey: 'whatsapp_share' },
    },
    update: { body: DEFAULT_WHATSAPP_TEMPLATE },
    create: {
      cityId: city.cityId,
      templateKey: 'whatsapp_share',
      body: DEFAULT_WHATSAPP_TEMPLATE,
    },
  });
  console.log(`✓ Default WhatsApp template seeded`);

  await prisma.messageTemplate.upsert({
    where: {
      cityId_templateKey: { cityId: city.cityId, templateKey: 'volunteer_credentials' },
    },
    // Do not overwrite an existing customised body on re-seed
    update: {},
    create: {
      cityId: city.cityId,
      templateKey: 'volunteer_credentials',
      body: DEFAULT_VOLUNTEER_CREDENTIALS_TEMPLATE,
    },
  });
  console.log(`✓ Default volunteer credentials template seeded`);

  // ---- 6. Captains ----
  const captainUsername = env('SEED_CAPTAIN_USERNAME', 'captain1');
  const captainPassword = env('SEED_CAPTAIN_PASSWORD', 'Change@Me123');
  const captainName = env('SEED_CAPTAIN_NAME', 'Pilot Captain');
  const captainPhone = env('SEED_CAPTAIN_PHONE', '9999999999');
  const passwordHash = await bcrypt.hash(captainPassword, 11);

  const captain = await prisma.user.upsert({
    where: { cityId_username: { cityId: city.cityId, username: captainUsername } },
    update: { fullName: captainName, phone: captainPhone, isCaptain: true, isVolunteer: true, isActive: true },
    create: {
      cityId: city.cityId,
      username: captainUsername,
      passwordHash,
      fullName: captainName,
      phone: captainPhone,
      isCaptain: true,
      isVolunteer: true,
      isActive: true,
    },
  });
  console.log(`✓ Captain seeded: username="${captain.username}" password from .env (change after first login)`);

  // Dummy captains for development/testing
  const dummyCaptains = [
    { username: 'captain2', fullName: 'Amit Shah', phone: '9988776655' },
    { username: 'captain3', fullName: 'Rajesh Mehta', phone: '9977665544' },
  ];
  const dummyHash = await bcrypt.hash('Change@Me123', 11);
  for (const dc of dummyCaptains) {
    await prisma.user.upsert({
      where: { cityId_username: { cityId: city.cityId, username: dc.username } },
      update: { fullName: dc.fullName, phone: dc.phone },
      create: {
        cityId: city.cityId,
        username: dc.username,
        passwordHash: dummyHash,
        fullName: dc.fullName,
        phone: dc.phone,
        isCaptain: true,
        isVolunteer: true,
        isActive: true,
      },
    });
  }
  console.log(`✓ ${dummyCaptains.length} dummy captains seeded (password: Change@Me123)`);

  console.log('\n✅ Seed complete.\n');
  console.log('Next steps:');
  console.log('  1. Start API:  pnpm dev:api');
  console.log('  2. Start web:  pnpm dev:web');
  console.log(`  3. Login:      ${captainUsername} / (password from .env)`);
}

main()
  .catch((e) => {
    console.error('❌ Seed failed:', e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
