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/warehouse.dart';
import '../../domain/repositories/warehouse_repository.dart';
import '../dtos/warehouse_dto.dart';

/// 창고(Warehouse) 마스터 API를 호출하는 원격 저장소.
class WarehouseRepositoryRemote implements WarehouseRepository {
  WarehouseRepositoryRemote({required ApiClient apiClient}) : _api = apiClient;

  final ApiClient _api;

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

  /// 창고 목록을 조회한다.
  @override
  Future<PaginatedResult<Warehouse>> list({
    int page = 1,
    int pageSize = 20,
    String? query,
    bool? isActive,
    bool includeZipcode = true,
  }) 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,
        if (includeZipcode) 'include': 'zipcode',
      },
      options: Options(responseType: ResponseType.json),
    );
    return WarehouseDto.parsePaginated(response.data ?? const {});
  }

  /// 창고를 생성한다.
  @override
  Future<Warehouse> create(WarehouseInput input) async {
    final response = await _api.post<Map<String, dynamic>>(
      _basePath,
      data: warehouseInputToJson(input),
      options: Options(responseType: ResponseType.json),
    );
    return WarehouseDto.fromJson(_api.unwrapAsMap(response)).toEntity();
  }

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

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

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