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 'package:superport_v2/features/approvals/step/domain/entities/approval_step_record.dart';
import 'package:superport_v2/features/approvals/step/domain/repositories/approval_step_repository.dart';
import '../dtos/approval_step_record_dto.dart';
import '../../domain/entities/approval_step_input.dart';

/// 결재 단계 API를 호출하는 원격 저장소 구현체.
class ApprovalStepRepositoryRemote implements ApprovalStepRepository {
  ApprovalStepRepositoryRemote({required ApiClient apiClient})
    : _api = apiClient;

  final ApiClient _api;

  static const _basePath = '${ApiRoutes.apiV1}/approval-steps';

  /// 결재 단계 목록을 조회한다.
  @override
  Future<PaginatedResult<ApprovalStepRecord>> list({
    int page = 1,
    int pageSize = 20,
    String? query,
    int? statusId,
    int? approverId,
    int? approvalId,
  }) async {
    final response = await _api.get<Map<String, dynamic>>(
      _basePath,
      query: {
        'page': page,
        'page_size': pageSize,
        if (query != null && query.isNotEmpty) 'q': query,
        if (statusId != null) ...{'status_id': statusId},
        if (approverId != null) 'approver_id': approverId,
        if (approvalId != null) 'approval_id': approvalId,
        'include': 'approval,approver,status',
      },
      options: Options(responseType: ResponseType.json),
    );

    return ApprovalStepRecordDto.parsePaginated(response.data);
  }

  /// 단일 결재 단계 상세를 조회한다.
  @override
  Future<ApprovalStepRecord> fetchDetail(int id) async {
    final response = await _api.get<Map<String, dynamic>>(
      '$_basePath/$id',
      options: Options(responseType: ResponseType.json),
    );
    return ApprovalStepRecordDto.fromJson(
      _api.unwrapAsMap(response),
    ).toEntity();
  }

  /// 결재 단계를 생성한다.
  @override
  Future<ApprovalStepRecord> create(ApprovalStepInput input) async {
    final response = await _api.post<Map<String, dynamic>>(
      _basePath,
      data: input.toPayload(),
      options: Options(responseType: ResponseType.json),
    );
    return ApprovalStepRecordDto.fromJson(
      _api.unwrapAsMap(response),
    ).toEntity();
  }

  /// 결재 단계를 수정한다.
  @override
  Future<ApprovalStepRecord> update(int id, ApprovalStepInput input) async {
    final response = await _api.patch<Map<String, dynamic>>(
      '$_basePath/$id',
      data: input.toPayload(),
      options: Options(responseType: ResponseType.json),
    );
    return ApprovalStepRecordDto.fromJson(
      _api.unwrapAsMap(response),
    ).toEntity();
  }

  /// 결재 단계를 비활성화한다.
  @override
  Future<void> delete(int id) async {
    await _api.delete<void>('$_basePath/$id');
  }

  /// 비활성화된 결재 단계를 복구한다.
  @override
  Future<ApprovalStepRecord> restore(int id) async {
    final response = await _api.post<Map<String, dynamic>>(
      '$_basePath/$id/restore',
      options: Options(responseType: ResponseType.json),
    );
    return ApprovalStepRecordDto.fromJson(
      _api.unwrapAsMap(response),
    ).toEntity();
  }
}
