import {
  AllowNull,
  BeforeCreate,
  BeforeUpdate,
  Column,
  DefaultScope,
  DeletedAt,
  Table,
  Unique,
} from "sequelize-typescript";
import { generateHash } from "src/common/hash";
import { TimestampModel } from "src/database/models/timestamp.model";

@DefaultScope(() => ({
  attributes: { exclude: ["password","deletedAt"] },
}))

@Table({ timestamps: true, tableName: "users" })
export class User extends TimestampModel {
  @Unique(true)
  @AllowNull(false)
  @Column
  username: string;

  @Unique(true)
  @AllowNull(false)
  @Column({ field: "phone_number" })
  phoneNumber: string;

  @Unique(true)
  @AllowNull(false)
  @Column
  email: string;

  @Column
  password: string;

  @AllowNull(false)
  @Column({ defaultValue: false })
  active: boolean;

  @Column({ field: "email_verification_sent_at" })
  emailVerificationSentAt: Date;

  @Column({ field: "email_verification_at" })
  emailVerificationAt: Date;

  @DeletedAt
  @Column({ field: "deleted_at" })
  deletedAt?: Date;

  @BeforeCreate
  static hashPassword(instance: User) {
    if (instance.password) {
      instance.password = generateHash(instance.password);
    }
  }

  @BeforeUpdate
  static hashPasswordIfNeeded(instance: User) {
    if (instance.password !== (instance as any)._previousDataValues.password) {
      instance.password = generateHash(instance.password);
    }
  }
}
