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

export interface IProduct {
  id: number;
  productName: string;
  productUnit: string;
  remainingStock: number;
  isDeleted: boolean;
  createdAt?: Date;
  updatedAt?: Date;
}

interface IProductCreationAttributes
  extends Optional<IProduct, "id" | "createdAt" | "updatedAt" | "isDeleted" | "remainingStock"> {}

class ProductModel
  extends Model<IProduct, IProductCreationAttributes>
  implements IProduct
{
  public id!: number;
  public productName!: string;
  public productUnit!: string;
  public remainingStock!: number;
  public isDeleted!: boolean;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
}

ProductModel.init(
  {
    id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
    productName: { type: DataTypes.STRING, allowNull: false },
    productUnit: { type: DataTypes.STRING, allowNull: false },
    remainingStock: { 
      type: DataTypes.INTEGER, 
      allowNull: false, 
      defaultValue: 0 
    },
    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: "products",
  }
);

const productValidationSchema = Joi.object({
  productName: Joi.string().min(1).max(100).required(),
  productUnit: Joi.string().min(1).max(50).required(),
  remainingStock: Joi.number().integer().min(0).optional(),
  isDeleted: Joi.boolean().optional(),
});

export { ProductModel, productValidationSchema };
