const { DataTypes } = require("sequelize");
const sequelizeConnect = require("../connection/db");
const PurchaseOrderDetails = require("./PurchaseOrderDetails");
const PurchaseOrderApprovals = require("./PurchaseOrderApprovals");
const SellersCompany = require("./SellersCompany");
const Suppliers = require("./Suppliers");

const PurchaseOrders = sequelizeConnect.define(
  "purchase_orders",
  {
    id: {
      type: DataTypes.BIGINT,
      primaryKey: true,
      allowNull: false,
      autoIncrement: true,
    },
    po_reference_no: {
      type: DataTypes.STRING(50),
      allowNull: false,
      unique: true,
    },
    supplier_id: {
      type: DataTypes.BIGINT,
      allowNull: false,
    },
    seller_id: {
      type: DataTypes.BIGINT,
      allowNull: false,
    },
    order_date: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
    },
    remarks: {
      type: DataTypes.TEXT,
      allowNull: true,
    },
    approval_status: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false,
    },
    sub_total: {
      type: DataTypes.DECIMAL(10, 2),
      allowNull: false,
      defaultValue: 0.0,
    },
    tax: {
      type: DataTypes.DECIMAL(10, 2),
      allowNull: false,
      defaultValue: 0.0,
    },
    total_amount: {
      type: DataTypes.DECIMAL(10, 2),
      allowNull: false,
      defaultValue: 0.0,
    },
    status: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: true,
    },
    created_by_admin_token: {
      type: DataTypes.STRING(500),
      allowNull: true,
    },
    updated_by_admin_token: {
      type: DataTypes.STRING(500),
      allowNull: true,
    },
  },
  {
    tableName: "purchase_orders",
    timestamps: true,
  }
);

PurchaseOrders.hasMany(PurchaseOrderDetails, {
  foreignKey: "purchase_order_id",
  as: "purchase_order_details",
});

PurchaseOrderDetails.belongsTo(PurchaseOrders, {
  foreignKey: "purchase_order_id",
  as: "purchase_order",
});

PurchaseOrders.hasMany(PurchaseOrderApprovals, {
  foreignKey: "purchase_order_id",
  as: "purchase_order_approvals",
});

PurchaseOrders.belongsTo(SellersCompany, {
  foreignKey: "seller_id",
  as: "seller_company",
});

PurchaseOrders.belongsTo(Suppliers, {
  foreignKey: "supplier_id",
  as: "supplier",
});

module.exports = PurchaseOrders;
