import bcrypt from 'bcryptjs';
import { z } from 'zod';
import * as usersRepo from '../repositories/users.repository.js';

export const updateUserSchema = z.object({
  name: z.string().check(z.minLength(2)).optional(),
  email: z.email().optional(),
  password: z.string().check(z.minLength(6)).optional(),
});

export async function getUser(id: string) {
  const user = await usersRepo.findUserById(id);
  if (!user) throw new Error('User not found');
  return { id: user.id, name: user.name, email: user.email, createdAt: user.createdAt };
}

export async function updateUser(id: string, input: z.infer<typeof updateUserSchema>) {
  const user = await usersRepo.findUserById(id);
  if (!user) throw new Error('User not found');

  const data: Parameters<typeof usersRepo.updateUser>[1] = { updatedAt: new Date() };

  if (input.name) data.name = input.name;
  if (input.email) data.email = input.email;
  if (input.password) data.password = await bcrypt.hash(input.password, 10);

  const updated = await usersRepo.updateUser(id, data);
  return { id: updated.id, name: updated.name, email: updated.email };
}

export async function deleteUser(id: string) {
  const user = await usersRepo.findUserById(id);
  if (!user) throw new Error('User not found');
  await usersRepo.deleteUser(id);
}