// models/commandes.js
const { DataTypes } = require('sequelize');
const sequelize = require('../config/database');

const Commande = sequelize.define('Commande', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  client_id: {
    type: DataTypes.INTEGER,
    allowNull: true
  },
  table_id: {
    type: DataTypes.INTEGER,
    allowNull: true
  },
  reservation_id: {
    type: DataTypes.INTEGER,
    allowNull: true
  },
  numero_commande: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true
  },
  statut: {
    type: DataTypes.ENUM,
    values: ['en_attente', 'en_preparation', 'prete', 'servie', 'annulee'],
    defaultValue: 'en_attente',
    allowNull: false
  },
  total_ht: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: false,
    defaultValue: 0.00
  },
  total_tva: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: false,
    defaultValue: 0.00
  },
  total_ttc: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: false,
    defaultValue: 0.00
  },
  mode_paiement: {
    type: DataTypes.ENUM,
    values: ['especes', 'carte_bancaire', 'cheque', 'virement', 'ticket_restaurant'],
    allowNull: true
  },
  commentaires: {
    type: DataTypes.TEXT,
    allowNull: true
  },
  serveur: {
    type: DataTypes.STRING,
    allowNull: true
  },
  date_commande: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW
  },
  date_service: {
    type: DataTypes.DATE,
    allowNull: true
  }
}, {
  tableName: 'commandes',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at',
  hooks: {
    beforeCreate: async (commande) => {
      if (!commande.numero_commande) {
        const timestamp = Date.now();
        commande.numero_commande = `CMD-${timestamp}`;
      }
    }
  }
});

module.exports = Commande;
