/**
 * Connection Attempts Model
 * Tracks all connection attempts to the backend
 */

module.exports = (sequelize, DataTypes) => {
	const ConnectionAttempt = sequelize.define(
		'connection_attempts',
		{
			id: {
				type: DataTypes.INTEGER,
				primaryKey: true,
				autoIncrement: true,
			},
			ip_address: {
				type: DataTypes.STRING(45),
				allowNull: false,
			},
			user_agent: {
				type: DataTypes.TEXT,
				allowNull: true,
			},
			isp_name: {
				type: DataTypes.STRING(100),
				allowNull: true,
			},
			isp_detected: {
				type: DataTypes.STRING(50),
				allowNull: true,
			},
			country: {
				type: DataTypes.STRING(50),
				allowNull: true,
			},
			city: {
				type: DataTypes.STRING(100),
				allowNull: true,
			},
			connection_status: {
				type: DataTypes.ENUM('success', 'failed', 'timeout'),
				allowNull: false,
			},
			error_type: {
				type: DataTypes.STRING(100),
				allowNull: true,
			},
			error_message: {
				type: DataTypes.TEXT,
				allowNull: true,
			},
			error_code: {
				type: DataTypes.STRING(50),
				allowNull: true,
			},
			attempt_timestamp: {
				type: DataTypes.DATE,
				defaultValue: DataTypes.NOW,
				allowNull: false,
			},
			response_time_ms: {
				type: DataTypes.INTEGER,
				allowNull: true,
			},
			endpoint_attempted: {
				type: DataTypes.STRING(255),
				allowNull: true,
			},
			request_method: {
				type: DataTypes.STRING(10),
				allowNull: true,
			},
			asn: {
				type: DataTypes.STRING(50),
				allowNull: true,
			},
			asn_org: {
				type: DataTypes.STRING(100),
				allowNull: true,
			},
		},
		{
			timestamps: false,
			tableName: 'connectionattempts',
			freezeTableName: true,
			indexes: [
				{ name: 'idx_connectionattempts_ip', fields: ['ip_address'] },
				{ name: 'idx_connectionattempts_status', fields: ['connection_status'] },
				{ name: 'idx_connectionattempts_timestamp', fields: ['attempt_timestamp'] },
				{ name: 'idx_connectionattempts_status_timestamp', fields: ['connection_status', 'attempt_timestamp'] },
				{ name: 'idx_connectionattempts_isp', fields: ['isp_detected'] },
				{ name: 'idx_connectionattempts_endpoint', fields: ['endpoint_attempted'] },
			],
		}
	);

	return ConnectionAttempt;
};
