import 'package:dio/dio.dart';
import 'package:intl/intl.dart';
import 'package:kmobile/data/models/transaction.dart';

abstract class TransactionRepository {
  Future<List<Transaction>> fetchTransactions(String accountNo,
      {DateTime? fromDate, DateTime? toDate});
}

class TransactionRepositoryImpl implements TransactionRepository {
  final Dio _dio;
  TransactionRepositoryImpl(this._dio);

  @override
  Future<List<Transaction>> fetchTransactions(String accountNo,
      {DateTime? fromDate, DateTime? toDate}) async {
    final queryParameters = <String, String>{};

    if (fromDate != null) {
      queryParameters['fromDate'] = DateFormat('ddMMyyyy').format(fromDate);
    }
    if (toDate != null) {
      queryParameters['toDate'] = DateFormat('ddMMyyyy').format(toDate);
    }

    final resp = await _dio.get(
      '/api/transactions/account/$accountNo',
      queryParameters: queryParameters.isNotEmpty ? queryParameters : null,
    );

    if (resp.statusCode != 200) {
      throw Exception(
        'Error fetching transactions: ${resp.statusCode} ${resp.statusMessage}',
      );
    }

    final List<dynamic> data = resp.data as List<dynamic>;
    return data
        .map((e) => Transaction.fromJson(e as Map<String, dynamic>))
        .toList();
  }
}
