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/vendor.dart';
import '../../domain/repositories/vendor_repository.dart';
import '../dtos/vendor_dto.dart';

/// 원격 구현체: 공통 ApiClient(Dio) 사용
class VendorRepositoryRemote implements VendorRepository {
  VendorRepositoryRemote({required ApiClient apiClient}) : _api = apiClient;

  final ApiClient _api;

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

  @override
  Future<PaginatedResult<Vendor>> list({
    int page = 1,
    int pageSize = 20,
    String? query,
    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 (isActive != null) 'active': isActive,
      },
      options: Options(responseType: ResponseType.json),
    );
    final map = response.data ?? const <String, dynamic>{};
    return VendorDto.parsePaginated(map);
  }

  @override
  Future<Vendor> create(VendorInput input) async {
    final response = await _api.post<Map<String, dynamic>>(
      _basePath,
      data: vendorInputToJson(input),
      options: Options(responseType: ResponseType.json),
    );
    return VendorDto.fromJson(_api.unwrapAsMap(response)).toEntity();
  }

  @override
  Future<Vendor> update(int id, VendorInput input) async {
    final payload = vendorInputToJson(input)..['id'] = id;
    final response = await _api.patch<Map<String, dynamic>>(
      '$_basePath/$id',
      data: payload,
      options: Options(responseType: ResponseType.json),
    );
    return VendorDto.fromJson(_api.unwrapAsMap(response)).toEntity();
  }

  @override
  Future<void> delete(int id) async {
    await _api.delete<void>('$_basePath/$id');
  }

  @override
  Future<Vendor> restore(int id) async {
    final response = await _api.post<Map<String, dynamic>>(
      '$_basePath/$id/restore',
      options: Options(responseType: ResponseType.json),
    );
    return VendorDto.fromJson(_api.unwrapAsMap(response)).toEntity();
  }
}
