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

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

@Scopes(() => ({
  role: () => ({
    include: [
      {model: Role.unscoped(), attributes: ['id', 'name', 'displayName', 'active']}
    ],
  })
}))

@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;

  @ForeignKey(() => Role)
  @Column({ field: "role_id" })
  roleId: number;

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

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

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

  @BelongsTo(() => Role)
  role: Role;

  @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);
    }
  }
}
