import 'package:dio/dio.dart';
import '../models/customer.dart';
import 'api_client.dart';

class CustomerService {
  final _client = ApiClient.instance;

  Future<CustomerListResponse> getCustomers({
    int page = 1,
    int pageSize = 20,
    String? search,
  }) async {
    final res = await _client.get('/customers', params: {
      'page': page,
      'pageSize': pageSize,
      if (search != null && search.isNotEmpty) 'search': search,
    });
    return CustomerListResponse.fromJson(res.data as Map<String, dynamic>);
  }

  Future<Customer> getCustomer(String id) async {
    final res = await _client.get('/customers/$id');
    return Customer.fromJson(res.data as Map<String, dynamic>);
  }

  Future<Customer> createCustomer(Map<String, dynamic> data) async {
    final res = await _client.post('/customers', data: data);
    return Customer.fromJson(res.data as Map<String, dynamic>);
  }

  Future<Customer> updateCustomer(String id, Map<String, dynamic> data) async {
    final res = await _client.patch('/customers/$id', data: data);
    return Customer.fromJson(res.data as Map<String, dynamic>);
  }

  Future<void> flagCustomer(String id, String reason) async {
    await _client.post('/customers/$id/flag', data: {'reason': reason});
  }

  Future<void> unflagCustomer(String id) async {
    await _client.delete('/customers/$id/flag');
  }

  Future<Customer> approveLicense(
      String id, String decision, {String? note}) async {
    final res = await _client.post('/customers/$id/approve-license',
        data: {'decision': decision, 'note': ?note});
    return Customer.fromJson(res.data as Map<String, dynamic>);
  }

  Future<Customer> uploadLicenseImage(String id, String filePath) async {
    final formData = FormData.fromMap({
      'file': await MultipartFile.fromFile(filePath),
    });
    final res = await _client.dio.post(
      '/customers/$id/license-image',
      data: formData,
      options: Options(headers: {'Content-Type': 'multipart/form-data'}),
    );
    final body = res.data;
    final payload = (body is Map<String, dynamic> && body.containsKey('data'))
        ? body['data']
        : body;
    return Customer.fromJson(payload as Map<String, dynamic>);
  }
}
