import type { IUserRepository } from '../../../domain/ports/user-repository'
import type { IPasswordHasher } from '../../../domain/ports/password-hasher'
import type { UserRole } from '../../../domain/entities/user'
import { AppError } from '../../../domain/errors/app-error'

export interface RegisterStaffInput {
  fullName: string
  email: string
  password: string
  role: UserRole
  discountLimitPct: number
}

export interface RegisterStaffOutput {
  id: string
  fullName: string
  email: string
  role: UserRole
}

export class RegisterStaff {
  constructor(
    private readonly userRepo: IUserRepository,
    private readonly hasher: IPasswordHasher,
  ) {}

  async execute(input: RegisterStaffInput): Promise<RegisterStaffOutput> {
    const exists = await this.userRepo.emailExists(input.email)
    if (exists) {
      throw new AppError('EMAIL_TAKEN', 409, 'Ya existe un usuario con ese email')
    }

    const passwordHash = await this.hasher.hash(input.password)

    const user = await this.userRepo.create({
      fullName: input.fullName,
      email: input.email,
      passwordHash,
      role: input.role,
      discountLimitPct: input.discountLimitPct,
    })

    return { id: user.id, fullName: user.fullName, email: user.email, role: user.role }
  }
}
