/**
 * Seed user: Rohit Mandiwal (dealer).
 * Creates user in users table and prints bcrypt hash for password login.
 *
 * User: email = rohitm_ext@royalenfield.com, name = Rohit Mandiwal, role = USER (dealer).
 * Password: Test@123
 *
 * After running, add to .env for password login:
 *   LOCAL_DEALER_2_EMAIL=rohitm_ext@royalenfield.com
 *   LOCAL_DEALER_2_PASSWORD_HASH=<hash printed below>
 * Login with username = rohitm_ext@royalenfield.com, password = Test@123
 */

import bcrypt from 'bcryptjs';
import { sequelize } from '../config/database';
import { User } from '../models/User';
import logger from '../utils/logger';

const EMAIL = 'rohitm_ext@royalenfield.com';
const OLD_EMAIL = 'rohit.m.ext@royalenfield.com';
const OKTA_SUB = 'local-ROHIT-MANDIWAL';
const PASSWORD = 'Test@123';
const DISPLAY_NAME = 'Rohit Mandiwal';
const FIRST_NAME = 'Rohit';
const LAST_NAME = 'Mandiwal';

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

    let user = await User.findOne({ where: { email: EMAIL } });
    if (!user) {
      const oldUser = await User.findOne({ where: { email: OLD_EMAIL } });
      if (oldUser) {
        await oldUser.update({ email: EMAIL });
        user = oldUser;
        logger.info('[Seed Rohit User] Updated existing user email to:', EMAIL);
      }
    }

    const userData = {
      email: EMAIL,
      oktaSub: OKTA_SUB,
      displayName: DISPLAY_NAME,
      firstName: FIRST_NAME,
      lastName: LAST_NAME,
      isActive: true,
      role: 'USER' as const,
      emailNotificationsEnabled: true,
      pushNotificationsEnabled: true,
      inAppNotificationsEnabled: true,
    };

    if (user) {
      await user.update(userData);
      logger.info('[Seed Rohit User] Updated user:', user.userId);
    } else {
      user = await User.create(userData);
      logger.info('[Seed Rohit User] Created user:', user.userId);
    }

    const hash = await bcrypt.hash(PASSWORD, 10);
    console.log('\n---------- Add these to your .env for password login ----------');
    console.log('LOCAL_DEALER_2_EMAIL=rohitm_ext@royalenfield.com');
    console.log(`LOCAL_DEALER_2_PASSWORD_HASH=${hash}`);
    console.log('----------------------------------------------------------------');
    console.log('Login: username = rohitm_ext@royalenfield.com, password = Test@123\n');
  } catch (error) {
    logger.error('[Seed Rohit User] Error:', error);
    throw error;
  }
}

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

export { seedRohitUser };
