/**
 * Demo RE Admin user for local login (no Okta).
 * Login: admin@example.com / Admin@123
 * User is created on server start if missing; password is verified in auth.service with a default hash.
 */

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

const ADMIN_EMAIL = 'admin@example.com';
const ADMIN_OKTA_SUB = 'local-ADMIN';
const ADMIN_PASSWORD = 'Admin@123';
const ADMIN_DISPLAY_NAME = 'RE Admin';

/** Ensure demo admin user exists in DB (called on server start). */
export async function ensureDemoAdminUser(): Promise<void> {
  try {
    let user = await User.findOne({ where: { email: ADMIN_EMAIL } });
    const userData = {
      email: ADMIN_EMAIL,
      oktaSub: ADMIN_OKTA_SUB,
      displayName: ADMIN_DISPLAY_NAME,
      firstName: 'RE',
      lastName: 'Admin',
      isActive: true,
      role: 'ADMIN' as const,
      emailNotificationsEnabled: true,
      pushNotificationsEnabled: true,
      inAppNotificationsEnabled: true,
    };
    if (user) {
      await user.update(userData);
    } else {
      await User.create(userData);
      logger.info('[Demo Admin] Created demo admin user (admin@example.com). Sign in with Admin@123');
    }
  } catch (err) {
    logger.warn('[Demo Admin] Could not ensure demo admin user:', err);
  }
}

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

    let user = await User.findOne({
      where: { email: ADMIN_EMAIL },
    });

    const userData = {
      email: ADMIN_EMAIL,
      oktaSub: ADMIN_OKTA_SUB,
      displayName: ADMIN_DISPLAY_NAME,
      firstName: 'RE',
      lastName: 'Admin',
      isActive: true,
      role: 'ADMIN' as const,
      emailNotificationsEnabled: true,
      pushNotificationsEnabled: true,
      inAppNotificationsEnabled: true,
    };

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

    const hash = await bcrypt.hash(ADMIN_PASSWORD, 10);
    console.log('\n---------- Add these to your .env ----------');
    console.log('ENABLE_LOCAL_ADMIN_LOGIN=true');
    console.log(`LOCAL_ADMIN_EMAIL=${ADMIN_EMAIL}`);
    console.log(`LOCAL_ADMIN_PASSWORD_HASH=${hash}`);
    console.log('---------------------------------------------\n');
    console.log('Login with:');
    console.log(`  Email:    ${ADMIN_EMAIL}`);
    console.log(`  Password: ${ADMIN_PASSWORD}`);
    console.log('---------------------------------------------\n');
    logger.info('[Seed Admin User] ✅ Done. Use the credentials above to log in as RE Admin.');
  } catch (error) {
    logger.error('[Seed Admin User] ❌ Error:', error);
    throw error;
  }
}

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

export { seedAdminUser };
