import 'dart:convert';
import 'package:hive_ce/hive.dart';
import 'package:worker/core/constants/storage_constants.dart';

part 'audit_log_model.g.dart';

@HiveType(typeId: HiveTypeIds.auditLogModel)
class AuditLogModel extends HiveObject {
  AuditLogModel({
    required this.logId,
    required this.userId,
    required this.action,
    required this.entityType,
    required this.entityId,
    this.oldValue,
    this.newValue,
    this.ipAddress,
    this.userAgent,
    required this.timestamp,
  });

  @HiveField(0)
  final int logId;
  @HiveField(1)
  final String userId;
  @HiveField(2)
  final String action;
  @HiveField(3)
  final String entityType;
  @HiveField(4)
  final String entityId;
  @HiveField(5)
  final String? oldValue;
  @HiveField(6)
  final String? newValue;
  @HiveField(7)
  final String? ipAddress;
  @HiveField(8)
  final String? userAgent;
  @HiveField(9)
  final DateTime timestamp;

  factory AuditLogModel.fromJson(Map<String, dynamic> json) => AuditLogModel(
    logId: json['log_id'] as int,
    userId: json['user_id'] as String,
    action: json['action'] as String,
    entityType: json['entity_type'] as String,
    entityId: json['entity_id'] as String,
    oldValue: json['old_value'] != null ? jsonEncode(json['old_value']) : null,
    newValue: json['new_value'] != null ? jsonEncode(json['new_value']) : null,
    ipAddress: json['ip_address'] as String?,
    userAgent: json['user_agent'] as String?,
    timestamp: DateTime.parse(json['timestamp'] as String),
  );

  Map<String, dynamic> toJson() => {
    'log_id': logId,
    'user_id': userId,
    'action': action,
    'entity_type': entityType,
    'entity_id': entityId,
    'old_value': oldValue != null ? jsonDecode(oldValue!) : null,
    'new_value': newValue != null ? jsonDecode(newValue!) : null,
    'ip_address': ipAddress,
    'user_agent': userAgent,
    'timestamp': timestamp.toIso8601String(),
  };
}
