/// Data Model: Price Document
///
/// Data model for price policy documents from API.
library;

import 'package:worker/features/price_policy/domain/entities/price_document.dart';

/// Price document data model
class PriceDocumentModel {
  /// Document title
  final String title;

  /// URL to download the document
  final String fileUrl;

  /// Last updated timestamp
  final String updatedAt;

  /// Constructor
  const PriceDocumentModel({
    required this.title,
    required this.fileUrl,
    required this.updatedAt,
  });

  /// Create from JSON
  factory PriceDocumentModel.fromJson(Map<String, dynamic> json) {
    return PriceDocumentModel(
      title: json['title'] as String? ?? '',
      fileUrl: json['file_url'] as String? ?? '',
      updatedAt: json['updated_at'] as String? ?? '',
    );
  }

  /// Convert to JSON
  Map<String, dynamic> toJson() {
    return {
      'title': title,
      'file_url': fileUrl,
      'updated_at': updatedAt,
    };
  }

  /// Convert to domain entity
  PriceDocument toEntity(DocumentCategory category) {
    return PriceDocument(
      title: title,
      fileUrl: fileUrl,
      updatedAt: _parseDateTime(updatedAt),
      category: category,
    );
  }

  /// Parse datetime string from API format
  /// Format: "2025-11-26 11:36:43"
  DateTime _parseDateTime(String dateTimeStr) {
    try {
      // Replace space with 'T' for ISO 8601 format
      final isoFormat = dateTimeStr.trim().replaceFirst(' ', 'T');
      return DateTime.parse(isoFormat);
    } catch (e) {
      // If parsing fails, return current datetime
      return DateTime.now();
    }
  }

  /// Create from domain entity
  factory PriceDocumentModel.fromEntity(PriceDocument entity) {
    return PriceDocumentModel(
      title: entity.title,
      fileUrl: entity.fileUrl,
      updatedAt: _formatDateTime(entity.updatedAt),
    );
  }

  /// Format datetime to API format
  static String _formatDateTime(DateTime dateTime) {
    return '${dateTime.year}-'
        '${dateTime.month.toString().padLeft(2, '0')}-'
        '${dateTime.day.toString().padLeft(2, '0')} '
        '${dateTime.hour.toString().padLeft(2, '0')}:'
        '${dateTime.minute.toString().padLeft(2, '0')}:'
        '${dateTime.second.toString().padLeft(2, '0')}';
  }

  @override
  String toString() {
    return 'PriceDocumentModel(title: $title, fileUrl: $fileUrl, updatedAt: $updatedAt)';
  }
}

/// API Response wrapper
class PricingApiResponse {
  /// List of price documents
  final List<PriceDocumentModel> message;

  const PricingApiResponse({required this.message});

  /// Create from JSON
  factory PricingApiResponse.fromJson(Map<String, dynamic> json) {
    final messageList = json['message'] as List<dynamic>? ?? [];
    return PricingApiResponse(
      message: messageList
          .map((item) => PriceDocumentModel.fromJson(item as Map<String, dynamic>))
          .toList(),
    );
  }

  /// Convert to JSON
  Map<String, dynamic> toJson() {
    return {
      'message': message.map((doc) => doc.toJson()).toList(),
    };
  }
}
