const { DataTypes } = require('sequelize');

module.exports = (sequelize) => {
  const Ticket = sequelize.define(
    'Ticket',
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },
      ticketId: {
        type: DataTypes.STRING(30),
        unique: true,
        allowNull: false,
        field: 'ticket_id',
      },
      userId: {
        type: DataTypes.UUID,
        allowNull: false,
        field: 'user_id',
      },
      category: {
        type: DataTypes.ENUM(
          'account',
          'trading',
          'deposit',
          'withdrawal',
          'verification',
          'security',
          'technical',
          'other'
        ),
        allowNull: false,
      },
      subcategory: {
        type: DataTypes.STRING(100),
        allowNull: true,
      },
      subject: {
        type: DataTypes.STRING(200),
        allowNull: false,
      },
      description: {
        type: DataTypes.TEXT,
        allowNull: false,
      },
      status: {
        type: DataTypes.ENUM('open', 'pending', 'in_progress', 'resolved', 'closed'),
        defaultValue: 'open',
        allowNull: false,
      },
      priority: {
        type: DataTypes.ENUM('low', 'medium', 'high', 'urgent'),
        defaultValue: 'medium',
        allowNull: false,
      },
      orderId: {
        type: DataTypes.STRING(100),
        allowNull: true,
        field: 'order_id',
      },
      transactionId: {
        type: DataTypes.STRING(100),
        allowNull: true,
        field: 'transaction_id',
      },
      attachments: {
        type: DataTypes.JSON,
        defaultValue: [],
      },
      lastReplyBy: {
        type: DataTypes.ENUM('user', 'support'),
        allowNull: true,
        field: 'last_reply_by',
      },
      lastReplyAt: {
        type: DataTypes.DATE,
        allowNull: true,
        field: 'last_reply_at',
      },
      rating: {
        type: DataTypes.TINYINT.UNSIGNED,
        allowNull: true,
        validate: { min: 1, max: 5 },
      },
      ratingComment: {
        type: DataTypes.STRING(500),
        allowNull: true,
        field: 'rating_comment',
      },
      closedAt: {
        type: DataTypes.DATE,
        allowNull: true,
        field: 'closed_at',
      },
    },
    {
      tableName: 'tickets',
      underscored: true,
      timestamps: true,
    }
  );

  Ticket.associate = (models) => {
    Ticket.hasMany(models.TicketMessage, {
      as: 'messages',
      foreignKey: 'ticketId',
    });
    Ticket.belongsTo(models.User, {
      foreignKey: 'userId',
    });
  };

  return Ticket;
};
