import 'package:dio/dio.dart';
import 'package:superport_v2/core/common/models/paginated_result.dart';
import 'package:superport_v2/core/network/api_client.dart';
import 'package:superport_v2/core/network/api_routes.dart';

import '../../domain/entities/customer.dart';
import '../../domain/repositories/customer_repository.dart';
import '../dtos/customer_dto.dart';

/// 고객(API) CRUD를 호출하는 원격 저장소 구현체.
class CustomerRepositoryRemote implements CustomerRepository {
  CustomerRepositoryRemote({required ApiClient apiClient}) : _api = apiClient;

  final ApiClient _api;

  static const _basePath = '${ApiRoutes.apiV1}/customers';

  /// 고객 목록을 조회한다.
  @override
  Future<PaginatedResult<Customer>> list({
    int page = 1,
    int pageSize = 20,
    String? query,
    bool? isPartner,
    bool? isGeneral,
    bool? isActive,
  }) async {
    final response = await _api.get<Map<String, dynamic>>(
      _basePath,
      query: {
        'page': page,
        'page_size': pageSize,
        if (query != null && query.isNotEmpty) 'q': query,
        if (isPartner != null) 'is_partner': isPartner,
        if (isGeneral != null) 'is_general': isGeneral,
        if (isActive != null) 'active': isActive,
      },
      options: Options(responseType: ResponseType.json),
    );
    return CustomerDto.parsePaginated(response.data ?? const {});
  }

  @override
  Future<Customer> fetchDetail(int id, {bool includeZipcode = true}) async {
    final response = await _api.get<Map<String, dynamic>>(
      '$_basePath/$id',
      query: {if (includeZipcode) 'include': 'zipcode'},
      options: Options(responseType: ResponseType.json),
    );
    return CustomerDto.fromJson(_api.unwrapAsMap(response)).toEntity();
  }

  /// 고객을 생성한다.
  @override
  Future<Customer> create(CustomerInput input) async {
    final response = await _api.post<Map<String, dynamic>>(
      _basePath,
      data: customerInputToJson(input),
      options: Options(responseType: ResponseType.json),
    );
    return CustomerDto.fromJson(_api.unwrapAsMap(response)).toEntity();
  }

  /// 고객 정보를 수정한다.
  @override
  Future<Customer> update(int id, CustomerInput input) async {
    final payload = customerInputToJson(input)..['id'] = id;
    final response = await _api.patch<Map<String, dynamic>>(
      '$_basePath/$id',
      data: payload,
      options: Options(responseType: ResponseType.json),
    );
    return CustomerDto.fromJson(_api.unwrapAsMap(response)).toEntity();
  }

  /// 고객을 삭제한다.
  @override
  Future<void> delete(int id) async {
    await _api.delete<void>('$_basePath/$id');
  }

  /// 삭제된 고객을 복구한다.
  @override
  Future<Customer> restore(int id) async {
    final response = await _api.post<Map<String, dynamic>>(
      '$_basePath/$id/restore',
      options: Options(responseType: ResponseType.json),
    );
    return CustomerDto.fromJson(_api.unwrapAsMap(response)).toEntity();
  }
}
