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

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

interface IShopPurchaseCreationAttributes
  extends Optional<
    IShopPurchase,
    "id" | "createdAt" | "updatedAt" | "isDeleted"
  > {}

class ShopPurchaseModel
  extends Model<IShopPurchase, IShopPurchaseCreationAttributes>
  implements IShopPurchase
{
  public id!: number;
  public shopId!: number;
  public shopName!: string;
  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;
}

ShopPurchaseModel.init(
  {
    id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
    shopId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: "shops", key: "id" },
    },
    shopName: { type: DataTypes.STRING, allowNull: false },
    productId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: "shop_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: "shop_purchases",
  }
);

const shopPurchaseValidationSchema = Joi.object({
  shopId: Joi.number().integer().required(),
  shopName: Joi.string().min(1).max(100).required(),
  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 { ShopPurchaseModel, shopPurchaseValidationSchema };
