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

export interface ICustomer {
  id: number;
  name: string;
  emailAddress: string;
  phoneNumber: string;
  address: string;
  isDeleted: boolean;
  createdAt?: Date;
  updatedAt?: Date;
}

interface ICustomerCreationAttributes
  extends Optional<
    ICustomer,
    "id" | "createdAt" | "updatedAt" | "phoneNumber" | "address" | "isDeleted"
  > {}

class CustomerModel
  extends Model<ICustomer, ICustomerCreationAttributes>
  implements ICustomer
{
  public id!: number;
  public name!: string;
  public emailAddress!: string;
  public phoneNumber!: string;
  public address!: string;
  public isDeleted!: boolean;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
}

CustomerModel.init(
  {
    id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
    name: { type: DataTypes.STRING, allowNull: false },
    emailAddress: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        isEmail: true,
      },
    },
    phoneNumber: { type: DataTypes.STRING, allowNull: true },
    address: { type: DataTypes.STRING, allowNull: true },
    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: "customers",
  }
);

const customerValidationSchema = Joi.object({
  name: Joi.string().min(1).max(255).required(),
  emailAddress: Joi.string().email().required(),
  phoneNumber: Joi.string().min(7).max(15).optional(),
  address: Joi.string().min(1).max(255).optional(),
  isDeleted: Joi.boolean().optional(),
});

export { CustomerModel, customerValidationSchema };
