/// Model de données TransactionApproval avec sérialisation JSON
library transaction_approval_model;

import 'package:json_annotation/json_annotation.dart';
import '../../domain/entities/transaction_approval.dart';

part 'transaction_approval_model.g.dart';

@JsonSerializable(explicitToJson: true)
class TransactionApprovalModel extends TransactionApproval {
  @JsonKey(
    fromJson: _approversFromJson,
    toJson: _approversToJson,
  )
  @override
  final List<ApproverAction> approvers;

  const TransactionApprovalModel({
    required super.id,
    required super.transactionId,
    required super.transactionType,
    required super.amount,
    super.currency,
    required super.requesterId,
    required super.requesterName,
    super.organizationId,
    required super.requiredLevel,
    required super.status,
    this.approvers = const [],
    super.rejectionReason,
    required super.createdAt,
    super.expiresAt,
    super.completedAt,
    super.metadata,
  }) : super(approvers: approvers);

  static List<ApproverAction> _approversFromJson(List<dynamic>? json) =>
      json?.map((e) => ApproverActionModel.fromJson(e as Map<String, dynamic>)).toList() ?? [];

  static List<Map<String, dynamic>> _approversToJson(List<ApproverAction>? approvers) =>
      approvers?.map((a) => ApproverActionModel(
            approverId: a.approverId,
            approverName: a.approverName,
            approverRole: a.approverRole,
            decision: a.decision,
            comment: a.comment,
            decidedAt: a.decidedAt,
          ).toJson()).toList() ?? [];

  factory TransactionApprovalModel.fromJson(Map<String, dynamic> json) =>
      _$TransactionApprovalModelFromJson(json);

  Map<String, dynamic> toJson() => _$TransactionApprovalModelToJson(this);

  factory TransactionApprovalModel.fromEntity(TransactionApproval entity) {
    return TransactionApprovalModel(
      id: entity.id,
      transactionId: entity.transactionId,
      transactionType: entity.transactionType,
      amount: entity.amount,
      currency: entity.currency,
      requesterId: entity.requesterId,
      requesterName: entity.requesterName,
      organizationId: entity.organizationId,
      requiredLevel: entity.requiredLevel,
      status: entity.status,
      approvers: entity.approvers,
      rejectionReason: entity.rejectionReason,
      createdAt: entity.createdAt,
      expiresAt: entity.expiresAt,
      completedAt: entity.completedAt,
      metadata: entity.metadata,
    );
  }
}

@JsonSerializable()
class ApproverActionModel extends ApproverAction {
  const ApproverActionModel({
    required super.approverId,
    required super.approverName,
    required super.approverRole,
    required super.decision,
    super.comment,
    super.decidedAt,
  });

  factory ApproverActionModel.fromJson(Map<String, dynamic> json) =>
      _$ApproverActionModelFromJson(json);

  Map<String, dynamic> toJson() => _$ApproverActionModelToJson(this);
}
