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/user.dart';
import '../../domain/repositories/user_repository.dart';
import '../dtos/user_dto.dart';

/// 사용자 마스터 API를 호출하는 원격 저장소.
class UserRepositoryRemote implements UserRepository {
  UserRepositoryRemote({required ApiClient apiClient}) : _api = apiClient;

  final ApiClient _api;

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

  /// 사용자 목록을 조회한다.
  @override
  Future<PaginatedResult<UserAccount>> list({
    int page = 1,
    int pageSize = 20,
    String? query,
    int? groupId,
    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 (groupId != null) 'group_id': groupId,
        if (isActive != null) 'is_active': isActive,
        'include': 'group',
      },
      options: Options(responseType: ResponseType.json),
    );
    return UserDto.parsePaginated(response.data ?? const {});
  }

  /// 사용자를 생성한다.
  @override
  Future<UserAccount> create(UserInput input) async {
    final response = await _api.post<Map<String, dynamic>>(
      _basePath,
      data: input.toPayload(),
      options: Options(responseType: ResponseType.json),
    );
    return UserDto.fromJson(_api.unwrapAsMap(response)).toEntity();
  }

  /// 사용자 정보를 수정한다.
  @override
  Future<UserAccount> update(int id, UserInput input) async {
    final payload = input.toPayload()..['id'] = id;
    final response = await _api.patch<Map<String, dynamic>>(
      '$_basePath/$id',
      data: payload,
      options: Options(responseType: ResponseType.json),
    );
    return UserDto.fromJson(_api.unwrapAsMap(response)).toEntity();
  }

  /// 로그인한 사용자의 정보를 수정한다.
  @override
  Future<UserAccount> updateMe(UserProfileUpdateInput input) async {
    final response = await _api.patch<Map<String, dynamic>>(
      '$_basePath/me',
      data: input.toPayload(),
      options: Options(responseType: ResponseType.json),
    );
    return UserDto.fromJson(_api.unwrapAsMap(response)).toEntity();
  }

  /// 관리자가 특정 사용자의 비밀번호를 재설정한다.
  @override
  Future<UserAccount> resetPassword(int id) async {
    final response = await _api.post<Map<String, dynamic>>(
      '$_basePath/$id/reset-password',
      options: Options(responseType: ResponseType.json),
    );
    return UserDto.fromJson(_api.unwrapAsMap(response)).toEntity();
  }

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

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