/// Data Model: Payment Model
///
/// Model for payment data with API serialization.
/// Not stored in local database.
library;

import 'package:worker/features/orders/domain/entities/payment.dart';

/// Payment Model
///
/// Model for API parsing only (no Hive storage).
class PaymentModel {
  /// Payment ID (e.g., "ACC-PAY-2025-00020")
  final String name;

  /// Payment posting date (stored as ISO string)
  final String postingDate;

  /// Amount paid
  final double paidAmount;

  /// Payment method (e.g., "Chuyển khoản")
  final String? modeOfPayment;

  /// Related invoice ID
  final String? invoiceId;

  /// Related order ID
  final String? orderId;

  const PaymentModel({
    required this.name,
    required this.postingDate,
    required this.paidAmount,
    this.modeOfPayment,
    this.invoiceId,
    this.orderId,
  });

  /// Create from JSON (API response)
  factory PaymentModel.fromJson(Map<String, dynamic> json) {
    return PaymentModel(
      name: json['name'] as String? ?? '',
      postingDate: json['posting_date'] as String? ?? '',
      paidAmount: (json['paid_amount'] as num?)?.toDouble() ?? 0.0,
      modeOfPayment: json['mode_of_payment'] as String?,
      invoiceId: json['invoice_id'] as String?,
      orderId: json['order_id'] as String?,
    );
  }

  /// Convert to JSON
  Map<String, dynamic> toJson() {
    return {
      'name': name,
      'posting_date': postingDate,
      'paid_amount': paidAmount,
      'mode_of_payment': modeOfPayment,
      'invoice_id': invoiceId,
      'order_id': orderId,
    };
  }

  /// Convert to domain entity
  Payment toEntity() {
    return Payment(
      name: name,
      postingDate: DateTime.tryParse(postingDate) ?? DateTime.now(),
      paidAmount: paidAmount,
      modeOfPayment: modeOfPayment,
      invoiceId: invoiceId,
      orderId: orderId,
    );
  }

  /// Create from domain entity
  factory PaymentModel.fromEntity(Payment entity) {
    return PaymentModel(
      name: entity.name,
      postingDate: entity.postingDate.toIso8601String().split('T').first,
      paidAmount: entity.paidAmount,
      modeOfPayment: entity.modeOfPayment,
      invoiceId: entity.invoiceId,
      orderId: entity.orderId,
    );
  }

  @override
  String toString() {
    return 'PaymentModel(name: $name, paidAmount: $paidAmount)';
  }
}
