const Sequelize = require("sequelize");
const sequelizeConnect = require("../connection/db");
const ProductVariation = require("./ProductVariation");
const ProductMenu = require("./ProductMenu");
const ProductImages = require("./ProductImages");
const DetailProductReviews = require("./DetailProductReviews");

const Products = sequelizeConnect.define(
  "products",
  {
    id: {
      type: Sequelize.BIGINT,
      primaryKey: true,
      allowNull: false,
      autoIncrement: true,
    },
    type_id: {
      type: Sequelize.BIGINT,
      allowNull: false,
      defaultValue: 0,
    },
    menu_id: {
      type: Sequelize.BIGINT,
      allowNull: false,
    },
    seller_id: {
      type: Sequelize.BIGINT,
      allowNull: false,
    },
    menu: {
      type: Sequelize.STRING(500),
      allowNull: true,
    },
    variant: {
      type: Sequelize.STRING(500),
      allowNull: true,
    },
    description: {
      type: Sequelize.STRING(500),
      allowNull: true,
    },
    price: {
      type: Sequelize.DECIMAL(10, 3),
      allowNull: true,
    },
    discounted_price: {
      type: Sequelize.DECIMAL(10, 2),
      allowNull: false,
      defaultValue: 0.0,
    },
    photo: {
      type: Sequelize.STRING(500),
      allowNull: true,
    },
    quantity_limit: {
      type: Sequelize.BIGINT,
      allowNull: true,
    },
    stocks: {
      type: Sequelize.BIGINT,
      allowNull: true,
    },
    available: {
      type: Sequelize.BOOLEAN,
      allowNull: false,
      defaultValue: true,
    },
    sku: {
      type: Sequelize.STRING(150),
      allowNull: true,
    },
    product_variation_id: {
      type: Sequelize.BIGINT,
      allowNull: true,
    },
    product_sub_variation_id: {
      type: Sequelize.BIGINT,
      allowNull: true,
    },
    seller_dashboard_src: {
      type: Sequelize.BOOLEAN,
      allowNull: false,
      defaultValue: true,
    },
  },
  {
    tableName: "products",
    timestamps: false,
  }
);

Products.hasMany(ProductVariation, {
  foreignKey: "product_id",
  as: "product_variations",
});

Products.belongsTo(ProductMenu, {
  foreignKey: "menu_id", // This should be the foreign key in the products table
  targetKey: "id", // This should be the primary key in the product_menu table
  as: "menus",
});

Products.hasMany(DetailProductReviews, {
  foreignKey: "product_id",
  as: "product_review",
});

Products.hasMany(ProductImages, {
  foreignKey: "product_id",
  as: "product_images",
});

module.exports = Products;
