import { userRepository } from '@/lib/repositories/userRepository';
import { authAdapter } from '@/lib/adapters/auth';
import { User, CreateUserInput } from '@/types/auth';

/**
 * Service para lógica de negocio de Usuarios/Auth
 */
export class AuthService {
  /**
   * Verificar credenciales y obtener usuario
   */
  async verifyCredentials(username: string, password: string): Promise<User | null> {
    return authAdapter.verifyCredentials(username, password);
  }

  /**
   * Crear un nuevo usuario
   */
  async createUser(
    data: CreateUserInput,
    creatorRole: 'USER' | 'ADMIN'
  ): Promise<{ id: string }> {
    // Verificar permisos (solo admin puede crear usuarios)
    if (creatorRole !== 'ADMIN') {
      throw new Error('No tienes permisos para crear usuarios');
    }

    // Verificar que el username sea único
    const existing = await userRepository.existsByUsername(data.username);
    if (existing) {
      throw new Error('El nombre de usuario ya está en uso');
    }

    // Hashear password
    const passwordHash = await authAdapter.hashPassword(data.password);

    // Crear usuario
    const user = await userRepository.create({
      name: data.name || data.username,
      username: data.username,
      passwordHash,
      role: data.role || 'USER',
    });

    return { id: user.id };
  }

  /**
   * Obtener todos los usuarios (solo admin)
   */
  async getAllUsers(): Promise<User[]> {
    return userRepository.findMany();
  }

  /**
   * Obtener un usuario por ID
   */
  async getUserById(id: string): Promise<User | null> {
    return userRepository.findById(id);
  }

  /**
   * Verificar si existen usuarios en el sistema
   */
  async hasUsers(): Promise<boolean> {
    const count = await userRepository.count();
    return count > 0;
  }
}

export const authService = new AuthService();
