import { userRepository } from '../repositories/userRepository';
import { CreateUserDto, UpdateUserDto, User } from '../models/User';
import { AppError } from '../middleware/errorHandler';

export const userService = {
  async getAll(): Promise<User[]> {
    return userRepository.findAll();
  },

  async getById(id: number): Promise<User> {
    const user = await userRepository.findById(id);
    if (!user) throw new AppError(404, `User ${id} not found`);
    return user;
  },

  async create(dto: CreateUserDto): Promise<User> {
    if (!dto.name?.trim()) throw new AppError(400, 'Name is required');
    if (!dto.email?.trim()) throw new AppError(400, 'Email is required');
    return userRepository.create(dto);
  },

  async update(id: number, dto: UpdateUserDto): Promise<User> {
    const updated = await userRepository.update(id, dto);
    if (!updated) throw new AppError(404, `User ${id} not found`);
    return updated;
  },

  async delete(id: number): Promise<void> {
    const deleted = await userRepository.delete(id);
    if (!deleted) throw new AppError(404, `User ${id} not found`);
  },
};
