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/group_permission.dart';
import '../../domain/repositories/group_permission_repository.dart';
import '../dtos/group_permission_dto.dart';

/// 그룹-메뉴 권한 API를 호출하는 원격 저장소.
class GroupPermissionRepositoryRemote implements GroupPermissionRepository {
  GroupPermissionRepositoryRemote({required ApiClient apiClient})
    : _api = apiClient;

  final ApiClient _api;

  static const _basePath = '${ApiRoutes.apiV1}/group-menu-permissions';

  /// 그룹 권한 목록을 조회한다.
  @override
  Future<PaginatedResult<GroupPermission>> list({
    int page = 1,
    int pageSize = 20,
    int? groupId,
    int? menuId,
    bool? isActive,
    bool includeDeleted = false,
  }) async {
    final response = await _api.get<Map<String, dynamic>>(
      _basePath,
      query: {
        'page': page,
        'page_size': pageSize,
        if (groupId != null) 'group_id': groupId,
        if (menuId != null) 'menu_id': menuId,
        if (isActive != null) 'active': isActive,
        if (includeDeleted) 'include_deleted': true,
        'include': 'group,menu',
      },
      options: Options(responseType: ResponseType.json),
    );
    return GroupPermissionDto.parsePaginated(response.data ?? const {});
  }

  /// 그룹 권한을 생성한다.
  @override
  Future<GroupPermission> create(GroupPermissionInput input) async {
    final response = await _api.post<Map<String, dynamic>>(
      _basePath,
      data: input.toPayload(),
      options: Options(responseType: ResponseType.json),
    );
    return GroupPermissionDto.fromJson(_api.unwrapAsMap(response)).toEntity();
  }

  /// 그룹 권한을 수정한다.
  @override
  Future<GroupPermission> update(int id, GroupPermissionInput 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 GroupPermissionDto.fromJson(_api.unwrapAsMap(response)).toEntity();
  }

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

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