import { Operador } from '@src/entity/Operador'
import { Request, Response } from 'express'
import { validate } from 'class-validator'
import { getRepository } from 'typeorm'

export class OperadorController {
  static async create (req: Request, res: Response) {
    const { usuario, secreto, admin } = req.body

    const operador = new Operador()

    operador.usuario = usuario
    operador.secreto = secreto
    operador.admin = admin

    const errors = await validate(operador)
    if (errors.length > 0) {
      res.status(400).send(errors)
    }

    operador.hashPassword()

    const repository = getRepository(Operador)
    try {
      await repository.save(operador)
    } catch (e) {
      res.status(409).send('username already in use')
    }
    res.status(201).send('User created')
  }

  static async getAll (req: Request, res: Response) {
    const repository = getRepository(Operador)
    const result = await repository.find({
      select: ['id', 'usuario', 'admin']
    })
    res.status(200).json(result)
  }

  static async getOne (req: Request, res: Response) {
    const id: number = +req.params.id
    const repository = getRepository(Operador)
    try {
      const operador = await repository.findOneOrFail(id, {
        select: ['id', 'usuario', 'admin']
      })
      res.status(200).json(operador)
    } catch (e) {
      res.status(404).send('User not found')
    }
  }

  static async remove (req: Request, res: Response) {
    const id = +req.params.id
    const repository = getRepository(Operador)
    try {
      const operador = await repository.findOneOrFail(id)
      repository.remove(operador)
      res.status(204).send()
    } catch (error) {
      res.status(404).send('User not found')
    }
  }
}
