/**
 * Seed dealer user for local login (Form 16A testing).
 * Creates:
 * 1. User with email testreflow@example.com, oktaSub local-TESTREFLOW (for dealer lookup)
 * 2. Dealer with dealer_principal_email_id = testreflow@example.com (via seed-test-dealer)
 * 3. Prints bcrypt hash for password T3$tr1Fl0w@12 — add to .env as LOCAL_DEALER_PASSWORD_HASH
 *
 * Login: username = TESTREFLOW, password = T3$tr1Fl0w@12
 * Enable: ENABLE_LOCAL_DEALER_LOGIN=true in .env
 */

import bcrypt from 'bcryptjs';
import { sequelize } from '../config/database';
import { User } from '../models/User';
import { seedTestDealer } from './seed-test-dealer';
import logger from '../utils/logger';

const DEALER_EMAIL = 'testreflow@example.com';
const DEALER_OKTA_SUB = 'local-TESTREFLOW';
const DEALER_PASSWORD = 'T3$tr1Fl0w@12';

async function seedDealerUser(): Promise<void> {
  try {
    logger.info('[Seed Dealer User] Starting...');

    // 1. Create or update User (so getDealerCodeForUser finds dealer by email)
    let user = await User.findOne({
      where: { email: DEALER_EMAIL },
    });

    const userData = {
      email: DEALER_EMAIL,
      oktaSub: DEALER_OKTA_SUB,
      displayName: 'Test Reflow Dealer',
      firstName: 'Test',
      lastName: 'Reflow',
      isActive: true,
    };

    if (user) {
      await user.update(userData);
      logger.info('[Seed Dealer User] ✅ Updated user:', user.userId);
    } else {
      user = await User.create({
        ...userData,
        emailNotificationsEnabled: true,
        pushNotificationsEnabled: true,
        inAppNotificationsEnabled: true,
        role: 'USER',
      });
      logger.info('[Seed Dealer User] ✅ Created user:', user.userId);
    }

    // 2. Ensure dealer exists (dealer_principal_email_id = testreflow@example.com)
    await seedTestDealer();

    // 3. Generate and print hash for .env
    const hash = await bcrypt.hash(DEALER_PASSWORD, 10);
    console.log('\n---------- Add these to your .env ----------');
    console.log('ENABLE_LOCAL_DEALER_LOGIN=true');
    console.log(`LOCAL_DEALER_PASSWORD_HASH=${hash}`);
    console.log('---------------------------------------------\n');
    logger.info('[Seed Dealer User] ✅ Done. Login with username=TESTREFLOW, password=<your password>');
  } catch (error) {
    logger.error('[Seed Dealer User] ❌ Error:', error);
    throw error;
  }
}

if (require.main === module) {
  sequelize
    .authenticate()
    .then(() => seedDealerUser())
    .then(() => process.exit(0))
    .catch((err) => {
      logger.error(err);
      process.exit(1);
    });
}

export { seedDealerUser };
