import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  OneToMany,
  Unique,
  UpdateDateColumn,
  CreateDateColumn
} from 'typeorm'
import * as bcrypt from 'bcrypt'
import { Log } from './Log'
import { IsString, IsBoolean } from 'class-validator'
import { Prestamo } from './Prestamo'

@Entity()
@Unique(['usuario'])
export class Operador {
  @PrimaryGeneratedColumn()
  id: number

  @Column()
  @IsString()
  usuario: string

  @Column()
  @IsString()
  secreto: string

  @Column()
  @IsBoolean()
  admin: boolean

  @Column()
  @UpdateDateColumn()
  updatedAt: Date

  @Column()
  @CreateDateColumn()
  createdAt: Date

  @OneToMany(
    (type) => Log,
    (log) => log.operador
  )
  logs: Log[]

  @OneToMany(
    (type) => Prestamo,
    (prestamo) => prestamo.operadorEntrega
  )
  entregas: Prestamo[]

  @OneToMany(
    (type) => Prestamo,
    (prestamo) => prestamo.operadorRegreso
  )
  regresos: Prestamo[]

  hashPassword () {
    this.secreto = bcrypt.hashSync(this.secreto, 10)
  }

  checkIfUnencryptedPasswordIsValid (unencryptedPassword: string) {
    return bcrypt.compareSync(unencryptedPassword, this.secreto)
  }
}
