/**
 * Purchase Order Model
 * Represents purchase orders (optional - GRN can exist without PO)
 */

module.exports = (sequelize, DataTypes) => {
  // Define PurchaseOrder model
  const PurchaseOrder = sequelize.define('PurchaseOrder', {
    // Primary key
    id: {
      type: DataTypes.BIGINT, // Use BIGINT for large scale
      primaryKey: true, // Set as primary key
      autoIncrement: true, // Auto-increment ID
    },
    // Foreign key to Vendor
    vendor_id: {
      type: DataTypes.BIGINT, // Match Vendor ID type
      allowNull: false, // Vendor ID is required
      references: {
        model: 'vendors', // Reference to vendors table
        key: 'id', // Reference to id column
      },
      onUpdate: 'CASCADE', // Cascade update on vendor update
    },
    // Purchase order status
    status: {
      type: DataTypes.ENUM('DRAFT', 'CONFIRMED', 'CLOSED'), // Enum for PO status
      defaultValue: 'DRAFT', // Default status is DRAFT
      allowNull: false, // Status is required
      validate: {
        isIn: [['DRAFT', 'CONFIRMED', 'CLOSED']], // Validate enum values
      },
    },
  }, {
    // Model options
    tableName: 'purchase_orders', // Explicit table name
    underscored: true, // Use snake_case for database columns
    timestamps: true, // Enable createdAt and updatedAt timestamps
    createdAt: 'created_at', // Map createdAt to created_at column
    updatedAt: 'updated_at', // Map updatedAt to updated_at column
    indexes: [
      // Index on vendor_id for faster lookups
      {
        fields: ['vendor_id'], // Index on vendor_id field
      },
      // Index on status for filtering by status
      {
        fields: ['status'], // Index on status field
      },
    ],
  });

  // Define model associations
  PurchaseOrder.associate = (models) => {
    // PurchaseOrder belongs to Vendor (many-to-one relationship)
    PurchaseOrder.belongsTo(models.Vendor, {
      foreignKey: 'vendor_id', // Foreign key in PurchaseOrder table
      as: 'vendor', // Alias for association
    });
    
    // PurchaseOrder has many GRNs (one-to-many relationship)
    PurchaseOrder.hasMany(models.GRN, {
      foreignKey: 'purchase_order_id', // Foreign key in GRNs table
      as: 'grns', // Alias for association
    });

    // PurchaseOrder has many PurchaseOrderItems (one-to-many relationship)
    PurchaseOrder.hasMany(models.PurchaseOrderItem, {
      foreignKey: 'purchase_order_id', // Foreign key in PurchaseOrderItems table
      as: 'items', // Alias for association
      onDelete: 'CASCADE', // Cascade delete items when PO is deleted
    });
  };

  // Return PurchaseOrder model
  return PurchaseOrder;
};

