import { sequelize } from '@config/database';
import { QueryTypes } from 'sequelize';
import logger from '@utils/logger';
import { ActivityType } from '@models/ActivityType';

/**
 * Default activity types from CLAIM_TYPES array
 * These will be seeded into the database with default item_code values (1-13)
 */
const DEFAULT_ACTIVITY_TYPES = [
  { title: 'Riders Mania Claims', itemCode: '1' },
  { title: 'Marketing Cost – Bike to Vendor', itemCode: '2' },
  { title: 'Media Bike Service', itemCode: '3' },
  { title: 'ARAI Motorcycle Liquidation', itemCode: '4' },
  { title: 'ARAI Certification – STA Approval CNR', itemCode: '5' },
  { title: 'Procurement of Spares/Apparel/GMA for Events', itemCode: '6' },
  { title: 'Fuel for Media Bike Used for Event', itemCode: '7' },
  { title: 'Motorcycle Buyback and Goodwill Support', itemCode: '8' },
  { title: 'Liquidation of Used Motorcycle', itemCode: '9' },
  { title: 'Motorcycle Registration CNR (Owned or Gifted by RE)', itemCode: '10' },
  { title: 'Legal Claims Reimbursement', itemCode: '11' },
  { title: 'Service Camp Claims', itemCode: '12' },
  { title: 'Corporate Claims – Institutional Sales PDI', itemCode: '13' }
];

/**
 * Seed default activity types if table is empty
 * Called automatically on server startup
 */
export async function seedDefaultActivityTypes(): Promise<void> {
  try {
    // Check if activity_types table exists
    const tableExists = await sequelize.query(
      `SELECT EXISTS (
        SELECT FROM information_schema.tables 
        WHERE table_schema = 'public' 
        AND table_name = 'activity_types'
      )`,
      { type: QueryTypes.SELECT }
    );

    const exists = tableExists && tableExists.length > 0 && (tableExists[0] as any).exists;
    
    if (!exists) {
      logger.warn('[ActivityType Seed] ⚠️  activity_types table does not exist. Please run migrations first (npm run migrate). Skipping seed.');
      return;
    }

    logger.info('[ActivityType Seed] Seeding default activity types (duplicates will be skipped automatically)...');

    // Get system user ID (first admin user) for created_by
    const systemUser = await sequelize.query(
      `SELECT user_id FROM users WHERE role = 'ADMIN' ORDER BY created_at ASC LIMIT 1`,
      { type: QueryTypes.SELECT }
    );

    let systemUserId: string | null = null;
    if (systemUser && systemUser.length > 0) {
      systemUserId = (systemUser[0] as any).user_id;
    }

    if (!systemUserId) {
      logger.warn('[ActivityType Seed] No admin user found. Activity types will be created without created_by reference.');
      // Use a placeholder UUID - this should not happen in production
      systemUserId = '00000000-0000-0000-0000-000000000000';
    }

    // Insert default activity types with proper handling
    let createdCount = 0;
    let updatedCount = 0;
    let skippedCount = 0;

    for (const activityType of DEFAULT_ACTIVITY_TYPES) {
      const { title, itemCode } = activityType;
      try {
        // Check if activity type already exists (active or inactive)
        const existing = await ActivityType.findOne({
          where: { title }
        });

        if (existing) {
          // If exists but inactive, reactivate it
          if (!existing.isActive) {
            // Update item_code if it's null (preserve if user has already set it)
            const updateData: any = {
              isActive: true,
              updatedBy: systemUserId
            };
            // Only set item_code if it's currently null (don't overwrite user edits)
            if (!existing.itemCode) {
              updateData.itemCode = itemCode;
            }
            await existing.update(updateData);
            updatedCount++;
            logger.debug(`[ActivityType Seed] Reactivated existing activity type: ${title}${!existing.itemCode ? ` (set item_code: ${itemCode})` : ''}`);
          } else {
            // Already exists and active
            // Update item_code if it's null (preserve if user has already set it)
            if (!existing.itemCode) {
              await existing.update({
                itemCode: itemCode,
                updatedBy: systemUserId
              } as any);
              logger.debug(`[ActivityType Seed] Updated item_code for existing activity type: ${title} (${itemCode})`);
            }
            skippedCount++;
            logger.debug(`[ActivityType Seed] Activity type already exists and active: ${title}`);
          }
        } else {
          // Create new activity type with default item_code
          await ActivityType.create({
            title,
            itemCode: itemCode,
            taxationType: null,
            sapRefNo: null,
            isActive: true,
            createdBy: systemUserId
          } as any);
          createdCount++;
          logger.debug(`[ActivityType Seed] Created new activity type: ${title} (item_code: ${itemCode})`);
        }
      } catch (error: any) {
        // Log error but continue with other activity types
        logger.warn(`[ActivityType Seed] Error processing ${title}: ${error?.message || String(error)}`);
        skippedCount++;
      }
    }

    // Verify how many are now active
    const result = await sequelize.query(
      'SELECT COUNT(*) as count FROM activity_types WHERE is_active = true',
      { type: QueryTypes.SELECT }
    );
    const totalCount = result && (result[0] as any).count ? (result[0] as any).count : 0;
    
    logger.info(`[ActivityType Seed] ✅ Activity type seeding complete. Created: ${createdCount}, Reactivated: ${updatedCount}, Skipped: ${skippedCount}, Total active: ${totalCount}`);
  } catch (error: any) {
    logger.error('[ActivityType Seed] ❌ Error seeding activity types:', {
      message: error?.message || String(error),
      stack: error?.stack,
      name: error?.name
    });
    // Don't throw - let server start even if seeding fails
  }
}

