import { userRepository } from '@/lib/repositories/user.repository';
import { hashPassword } from '@/lib/auth/password';
import { HttpError } from '@/lib/auth/session';
import { CreateUserInput, UpdateUserInput } from '@/lib/validators';

export const userService = {
  list: () => userRepository.listAll(),

  async create(input: CreateUserInput) {
    const existing = await userRepository.findByEmail(input.email);
    if (existing) throw new HttpError(409, 'A user with this email already exists');

    const password = await hashPassword(input.password);
    return userRepository.create({
      name: input.name,
      email: input.email,
      password,
      role: input.role,
    });
  },

  async update(id: number, input: UpdateUserInput) {
    const existing = await userRepository.findById(id);
    if (!existing) throw new HttpError(404, 'User not found');

    const data: Record<string, unknown> = {};
    if (input.name !== undefined) data.name = input.name;
    if (input.role !== undefined) data.role = input.role;
    if (input.password) data.password = await hashPassword(input.password);

    return userRepository.update(id, data);
  },

  async delete(id: number, actingUserId: number) {
    if (id === actingUserId) {
      throw new HttpError(400, 'You cannot delete your own account');
    }
    const existing = await userRepository.findById(id);
    if (!existing) throw new HttpError(404, 'User not found');
    return userRepository.delete(id);
  },
};
