/**
 * Seed Test Dealer
 * Creates a test dealer record in the dealers table for testing purposes
 * 
 * This creates a dealer with:
 * - domain_id: testreflow@example.com
 * - dealer_principal_email_id: testreflow@example.com
 * - dealer_principal_name: TEST REFLOW
 * - Random codes for sales_code, gear_code, and dlrcode to avoid conflicts
 */

import { sequelize } from '../config/database';
import { Dealer } from '../models/Dealer';
import { Op } from 'sequelize';
import logger from '../utils/logger';

/**
 * Generate a random 4-digit code
 * Checks for existing codes to avoid conflicts
 */
async function generateUniqueCode(
  field: 'salesCode' | 'serviceCode' | 'gearCode' | 'gmaCode' | 'dlrcode',
  existingCodes: Set<string>
): Promise<string> {
  let attempts = 0;
  const maxAttempts = 100;

  while (attempts < maxAttempts) {
    // Generate random 4-digit number (1000-9999)
    const randomCode = String(Math.floor(1000 + Math.random() * 9000));

    // Check if code already exists in database
    const existing = await Dealer.findOne({
      where: {
        [field]: randomCode
      }
    });

    // Also check if we've already generated this code in this run
    if (!existing && !existingCodes.has(randomCode)) {
      existingCodes.add(randomCode);
      return randomCode;
    }

    attempts++;
  }

  // Fallback: use timestamp-based code if random generation fails
  const timestampCode = String(Date.now()).slice(-4);
  logger.warn(`[Seed Test Dealer] Using timestamp-based code for ${field}: ${timestampCode}`);
  return timestampCode;
}

async function seedTestDealer(): Promise<void> {
  try {
    logger.info('[Seed Test Dealer] Starting test dealer seeding...');

    // Check if test dealer already exists
    const existingDealer = await Dealer.findOne({
      where: {
        [Op.or]: [
          { domainId: 'testreflow@example.com' },
          { dealerPrincipalEmailId: 'testreflow@example.com' }
        ]
      }
    });

    // Generate unique codes
    const existingCodes = new Set<string>();
    const salesCode = await generateUniqueCode('salesCode', existingCodes);
    const serviceCode = await generateUniqueCode('serviceCode', existingCodes);
    const gearCode = await generateUniqueCode('gearCode', existingCodes);
    const gmaCode = await generateUniqueCode('gmaCode', existingCodes);
    const dlrcode = await generateUniqueCode('dlrcode', existingCodes);

    const dealerData = {
      salesCode,
      serviceCode,
      gearCode,
      gmaCode,
      region: 'TEST',
      dealership: 'TEST REFLOW DEALERSHIP',
      state: 'Test State',
      district: 'Test District',
      city: 'Test City',
      location: 'Test Location',
      cityCategoryPst: 'A',
      layoutFormat: 'A',
      tierCityCategory: 'Tier 1 City',
      onBoardingCharges: null,
      date: new Date().toISOString().split('T')[0], // Current date in YYYY-MM-DD format
      singleFormatMonthYear: (() => {
        const now = new Date();
        const month = now.toLocaleDateString('en-US', { month: 'short' });
        const year = now.getFullYear();
        return `${month}-${year}`; // e.g., "Dec-2025" (format: "MMM-YYYY")
      })(),
      domainId: 'testreflow@example.com',
      replacement: null,
      terminationResignationStatus: null,
      dateOfTerminationResignation: null,
      lastDateOfOperations: null,
      oldCodes: null,
      branchDetails: null,
      dealerPrincipalName: 'TEST REFLOW',
      dealerPrincipalEmailId: 'testreflow@example.com',
      dpContactNumber: '9998887776',
      dpContacts: 'TEST CONTACT',
      showroomAddress: 'No. 335, RE Test Road, Bengaluru - 560098, Karnataka',
      showroomPincode: '560098',
      workshopAddress: 'Workshop Area B, Test Location',
      workshopPincode: '560098',
      locationDistrict: 'Bangalore',
      stateWorkshop: 'Karnataka',
      noOfStudios: 0,
      websiteUpdate: 'Yes',
      gst: '29AAACE3882D1ZZ', // Test GST
      pan: 'AAACE3882D',
      firmType: 'Test Firm',
      propManagingPartnersDirectors: 'TEST REFLOW',
      totalPropPartnersDirectors: 'TEST REFLOW',
      docsFolderLink: null,
      workshopGmaCodes: null,
      existingNew: 'New',
      dlrcode,
      isActive: true
    };

    if (existingDealer) {
      logger.info('[Seed Test Dealer] Test dealer already exists, updating...');

      // Update existing dealer
      await existingDealer.update(dealerData);

      logger.info(`[Seed Test Dealer] ✅ Updated test dealer: ${existingDealer.dealerId}`);
      logger.info(`[Seed Test Dealer]   - Domain ID: ${dealerData.domainId}`);
      logger.info(`[Seed Test Dealer]   - Dealer Principal: ${dealerData.dealerPrincipalName}`);
      logger.info(`[Seed Test Dealer]   - Sales Code: ${dealerData.salesCode}`);
      logger.info(`[Seed Test Dealer]   - Gear Code: ${dealerData.gearCode}`);
      logger.info(`[Seed Test Dealer]   - Dealer Code (dlrcode): ${dealerData.dlrcode}`);
    } else {
      // Create new dealer
      const newDealer = await Dealer.create(dealerData);

      logger.info(`[Seed Test Dealer] ✅ Created test dealer: ${newDealer.dealerId}`);
      logger.info(`[Seed Test Dealer]   - Domain ID: ${dealerData.domainId}`);
      logger.info(`[Seed Test Dealer]   - Dealer Principal: ${dealerData.dealerPrincipalName}`);
      logger.info(`[Seed Test Dealer]   - Sales Code: ${dealerData.salesCode}`);
      logger.info(`[Seed Test Dealer]   - Gear Code: ${dealerData.gearCode}`);
      logger.info(`[Seed Test Dealer]   - Dealer Code (dlrcode): ${dealerData.dlrcode}`);
    }

    logger.info('[Seed Test Dealer] ✅ Test dealer seeding completed successfully');
  } catch (error) {
    logger.error('[Seed Test Dealer] ❌ Error seeding test dealer:', error);
    throw error;
  }
}

// Run if called directly
if (require.main === module) {
  sequelize
    .authenticate()
    .then(() => {
      logger.info('[Seed Test Dealer] Database connection established');
      return seedTestDealer();
    })
    .then(() => {
      logger.info('[Seed Test Dealer] Seeding completed');
      process.exit(0);
    })
    .catch((error) => {
      logger.error('[Seed Test Dealer] Seeding failed:', error);
      process.exit(1);
    });
}

export { seedTestDealer };

