import bcrypt from 'bcryptjs';
import { storage } from './storage';
import { type User, type InsertUser } from '@shared/schema';

export async function hashPassword(password: string): Promise<string> {
  const saltRounds = 10;
  return await bcrypt.hash(password, saltRounds);
}

export async function comparePasswords(plainPassword: string, hashedPassword: string): Promise<boolean> {
  return await bcrypt.compare(plainPassword, hashedPassword);
}

export async function authenticateUser(username: string, password: string): Promise<User | null> {
  try {
    const user = await storage.getUserByUsername(username);
    if (!user || !user.isActive) {
      return null;
    }

    const isValidPassword = await comparePasswords(password, user.password);
    if (!isValidPassword) {
      return null;
    }

    return user;
  } catch (error) {
    console.error('Authentication error:', error);
    return null;
  }
}

export async function createFirstAdminUser(): Promise<void> {
  try {
    // Check if admin user already exists
    const existingUser = await storage.getUserByUsername('ceo@openweb.co.za');
    if (existingUser) {
      console.log('Admin user already exists');
      return;
    }

    // Create the first admin user
    const hashedPassword = await hashPassword('TrainPlane1526!!@');
    const adminUser: InsertUser = {
      username: 'ceo@openweb.co.za',
      password: hashedPassword,
      name: 'Keoma Wright',
      mobileNumber: '0826987888',
      role: 'admin',
      isActive: true
    };

    await storage.createUser(adminUser);
    console.log('First admin user created successfully');
  } catch (error) {
    console.error('Error creating first admin user:', error);
  }
}