import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/network/api_client.dart';
import '../../app.dart';
import '../../shared/models/pagination_model.dart';
import 'expense_model.dart';

final expenseApiProvider = Provider<ExpenseApi>(
  (ref) => ExpenseApi(ref.read(apiClientProvider)),
);

class ExpenseApi {
  final ApiClient _client;
  ExpenseApi(this._client);

  Future<PaginatedData<ExpenseModel>> fetchList({
    String status = '',
    int page = 1,
    int size = 20,
  }) async {
    final response = await _client.get<Map<String, dynamic>>(
      '/expense/list',
      queryParameters: {'status': status, 'page': page, 'size': size},
    );
    final data = response.data!;
    final list = (data['list'] as List<dynamic>)
        .map((e) => ExpenseModel.fromJson(e as Map<String, dynamic>))
        .toList();
    return PaginatedData(
      list: list,
      page: data['page'] as int,
      size: data['size'] as int,
      total: data['total'] as int,
    );
  }

  Future<ExpenseModel> fetchDetail(String id) async {
    final response = await _client.get<Map<String, dynamic>>(
      '/expense/detail/$id',
    );
    return ExpenseModel.fromJson(response.data!);
  }

  Future<void> submit(ExpenseModel expense) async {
    await _client.post('/expense/apply', data: expense.toJson());
  }

  Future<void> saveDraft(ExpenseModel expense) async {
    await _client.put('/expense/draft', data: expense.toJson());
  }
}
