import { DataTypes, Model, Optional } from "sequelize";
import Joi from "joi";
import sequelize from "../middlewears/sequelize";

export enum UserRole {
  Admin = "Admin",
  Shopkeeper = "Shopkeeper",
  Tailor = "Tailor",
  Master = "Master",
}

export interface IUserManagement {
  id: number;
  name: string;
  phoneNumber: string;
  role: UserRole;
  hasShopAccess: boolean;
  hasUserAccess: boolean;
  hasOrderAccess: boolean;
  hasSizeDefinitionAccess: boolean;
  isDeleted: boolean;
  createdAt?: Date;
  updatedAt?: Date;
}

interface IUserManagementCreationAttributes
  extends Optional<
    IUserManagement,
    | "id"
    | "createdAt"
    | "updatedAt"
    | "isDeleted"
    | "hasShopAccess"
    | "hasUserAccess"
    | "hasOrderAccess"
    | "hasSizeDefinitionAccess"
  > {}

class UserManagementModel
  extends Model<IUserManagement, IUserManagementCreationAttributes>
  implements IUserManagement
{
  public id!: number;
  public name!: string;
  public phoneNumber!: string;
  public role!: UserRole;
  public hasShopAccess!: boolean;
  public hasUserAccess!: boolean;
  public hasOrderAccess!: boolean;
  public hasSizeDefinitionAccess!: boolean;
  public isDeleted!: boolean;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
}

UserManagementModel.init(
  {
    id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
    name: { type: DataTypes.STRING, allowNull: false },
    phoneNumber: { type: DataTypes.STRING, allowNull: false },
    role: {
      type: DataTypes.ENUM(...Object.values(UserRole)),
      allowNull: false,
      defaultValue: UserRole.Admin,
    },
    hasShopAccess: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false,
    },
    hasUserAccess: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false,
    },
    hasOrderAccess: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false,
    },
    hasSizeDefinitionAccess: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false,
    },
    isDeleted: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false,
    },
    createdAt: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
    },
    updatedAt: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
    },
  },
  {
    sequelize,
    tableName: "user_managements",
  }
);

const userManagementValidationSchema = Joi.object({
  name: Joi.string().min(1).max(100).required(),
  phoneNumber: Joi.string().min(7).max(15).required(),
  role: Joi.string()
    .valid(...Object.values(UserRole))
    .optional(),
  hasShopAccess: Joi.boolean().optional(),
  hasUserAccess: Joi.boolean().optional(),
  hasOrderAccess: Joi.boolean().optional(),
  hasSizeDefinitionAccess: Joi.boolean().optional(),
  isDeleted: Joi.boolean().optional(),
});

export { UserManagementModel, userManagementValidationSchema };
