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

final expenseApplicationApiProvider = Provider<ExpenseApplicationApi>(
  (ref) => ExpenseApplicationApi(ref.read(apiClientProvider)),
);

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

  Future<PaginatedData<ExpenseApplicationModel>> fetchList({
    String status = '',
    int page = 1,
    int size = 20,
  }) async {
    final response = await _client.get<Map<String, dynamic>>(
      '/expense-apply/list',
      queryParameters: {'status': status, 'page': page, 'size': size},
    );
    final data = response.data!;
    final list = (data['list'] as List<dynamic>)
        .map((e) => ExpenseApplicationModel.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<ExpenseApplicationModel> fetchDetail(String id) async {
    final response = await _client.get<Map<String, dynamic>>(
      '/expense-apply/detail/$id',
    );
    return ExpenseApplicationModel.fromJson(response.data!);
  }

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

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