import bcrypt from 'bcryptjs'; import { eq } from 'drizzle-orm'; import { db } from '../../db/client'; import { users } from '../../db/schema/users'; import type { LoginData, RegisterData } from './auth.schema'; export async function registerUser(data: RegisterData) { const existingUser = await db.select().from(users).where(eq(users.email, data.email)).limit(1); if (existingUser.length > 0) { throw new Error('Email já está em uso.'); } const salt = await bcrypt.genSalt(10); const passwordHash = await bcrypt.hash(data.password, salt); const [newUser] = await db.insert(users).values({ name: data.name, email: data.email, password_hash: passwordHash, gross_salary: data.gross_salary || 0, }).returning(); const { password_hash, ...userWithoutPassword } = newUser; return userWithoutPassword; } export async function loginUser(data: LoginData) { const [user] = await db.select().from(users).where(eq(users.email, data.email)).limit(1); if (!user) { throw new Error('Email ou senha inválidos.'); } const isValid = await bcrypt.compare(data.password, user.password_hash); if (!isValid) { throw new Error('Email ou senha inválidos.'); } const { password_hash, ...userWithoutPassword } = user; return userWithoutPassword; }