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

export interface IPurchase {
  id: number;
  productId: number;
  productName: string;
  productUnit: string;
  quantity: number;
  totalPrice: number;
  perUnitPrice: number;
  isDeleted: boolean;
  createdAt?: Date;
  updatedAt?: Date;
}

interface IPurchaseCreationAttributes
  extends Optional<IPurchase, "id" | "createdAt" | "updatedAt" | "isDeleted"> {}

class PurchaseModel
  extends Model<IPurchase, IPurchaseCreationAttributes>
  implements IPurchase
{
  public id!: number;
  public productId!: number;
  public productName!: string;
  public productUnit!: string;
  public quantity!: number;
  public totalPrice!: number;
  public perUnitPrice!: number;
  public isDeleted!: boolean;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
}

PurchaseModel.init(
  {
    id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
    productId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: "products", key: "id" },
    },
    productName: { type: DataTypes.STRING, allowNull: false },
    productUnit: { type: DataTypes.STRING, allowNull: false },
    quantity: { type: DataTypes.INTEGER, allowNull: false },
    totalPrice: {
      type: DataTypes.DECIMAL(10, 2),
      allowNull: false,
    },
    perUnitPrice: {
      type: DataTypes.DECIMAL(10, 2),
      allowNull: 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: "purchases",
  }
);

const purchaseValidationSchema = Joi.object({
  productId: Joi.number().integer().required(),
  productName: Joi.string().min(1).max(100).required(),
  productUnit: Joi.string().min(1).max(50).required(),
  quantity: Joi.number().integer().min(1).required(),
  totalPrice: Joi.number().min(0).required(),
  perUnitPrice: Joi.number().min(0).required(),
  isDeleted: Joi.boolean().optional(),
});

export { PurchaseModel, purchaseValidationSchema };
