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

export interface IShopProduct {
  id: number;
  shopId: number;
  shopName: string;
  shopProductName: string;
  shopProductUnit: string;
  remainingStock: number;
  createdAt?: Date;
  updatedAt?: Date;
  isDeleted: boolean;
}

interface IShopProductCreationAttributes
  extends Optional<
    IShopProduct,
    "id" | "createdAt" | "updatedAt" | "isDeleted" | "remainingStock"
  > {}

class ShopProductModel
  extends Model<IShopProduct, IShopProductCreationAttributes>
  implements IShopProduct
{
  public id!: number;
  public shopId!: number;
  public shopName!: string;
  public shopProductName!: string;
  public shopProductUnit!: string;
  public remainingStock!: number;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
  public isDeleted!: boolean;
}

ShopProductModel.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 },
    shopProductName: { type: DataTypes.STRING, allowNull: false },
    shopProductUnit: { type: DataTypes.STRING, allowNull: false },
    remainingStock: { 
      type: DataTypes.INTEGER, 
      allowNull: false, 
      defaultValue: 0 
    },
    createdAt: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
    },
    updatedAt: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
    },
    isDeleted: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false,
    },
  },
  {
    sequelize,
    tableName: "shop_products",
  }
);

const shopProductValidationSchema = Joi.object({
  shopId: Joi.number().integer().required(),
  shopName: Joi.string().min(1).max(100).required(),
  shopProductName: Joi.string().min(1).max(100).required(),
  shopProductUnit: Joi.string().min(1).max(50).required(),
  remainingStock: Joi.number().integer().min(0).optional(),
  isDeleted: Joi.boolean().optional(),
});

export { ShopProductModel, shopProductValidationSchema };
