import {
  Table,
  Column,
  CreatedAt,
  UpdatedAt,
  Model,
  DataType,
  BeforeCreate,
  BeforeUpdate,
  PrimaryKey,
  AutoIncrement,
  Default,
  HasMany,
  BelongsToMany,
  BelongsTo,
  ForeignKey
} from "sequelize-typescript";
import { hash, compare } from "bcryptjs";
import Ticket from "./Ticket";
import Queue from "./Queue";
import UserQueue from "./UserQueue";
import UserOnlineTime from "./UserOnlineTime"; 
import Position from "./Position"

@Table
class User extends Model<User> {
  @PrimaryKey
  @AutoIncrement
  @Column
  id: number;

  @Column
  name: string;

  @Column
  email: string;

  @Column(DataType.VIRTUAL)
  password: string;

  @Column
  passwordHash: string;

  @Default(0)
  @Column
  tokenVersion: number; 

  @Column
  secondaryId: string;

  @Column
  transferToOtherQueues: boolean;

  @Column
  identifier: string;
  
  @Default("admin")
  @Column
  profile: string;

  @CreatedAt
  createdAt: Date;

  @UpdatedAt
  updatedAt: Date;
  @HasMany(() => Ticket)
  tickets: Ticket[];

  @HasMany(() => UserOnlineTime)
  UserOnlineTime: UserOnlineTime[];

  @BelongsToMany(() => Queue, () => UserQueue)
  queues: Queue[];

  @ForeignKey(() => Position)
  @Column
  positionId: number;

  @BelongsTo(() => Position)
  position: Position;

  @BeforeUpdate
  @BeforeCreate
  static hashPassword = async (instance: User): Promise<void> => {
    if (instance.password) {
      instance.passwordHash = await hash(instance.password, 8);
    }
  };

  public checkPassword = async (password: string): Promise<boolean> => {
    return compare(password, this.getDataValue("passwordHash"));
  };
}

export default User;
