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/approval_draft.dart';
import '../../domain/repositories/approval_draft_repository.dart';
import '../dtos/approval_draft_dto.dart';

/// 결재 초안을 원격 저장소로 관리한다.
class ApprovalDraftRepositoryRemote implements ApprovalDraftRepository {
  ApprovalDraftRepositoryRemote({required ApiClient apiClient})
    : _api = apiClient;

  final ApiClient _api;

  @override
  Future<PaginatedResult<ApprovalDraftSummary>> list(
    ApprovalDraftListFilter filter,
  ) async {
    final query = ApiClient.buildQuery(
      page: filter.page,
      pageSize: filter.pageSize,
      filters: {
        'requester_id': filter.requesterId,
        if (filter.transactionId != null)
          'transaction_id': filter.transactionId,
        if (filter.includeExpired) 'include_expired': filter.includeExpired,
      },
    );
    final response = await _api.get<Map<String, dynamic>>(
      ApiRoutes.approvalDrafts,
      query: query,
      options: Options(responseType: ResponseType.json),
    );
    return ApprovalDraftDto.parsePaginated(response.data);
  }

  @override
  Future<ApprovalDraftDetail?> fetch({
    required int id,
    required int requesterId,
  }) async {
    final query = ApiClient.buildQuery(filters: {'requester_id': requesterId});
    final response = await _api.get<Map<String, dynamic>>(
      ApiClient.buildPath(ApiRoutes.approvalDrafts, [id]),
      query: query,
      options: Options(responseType: ResponseType.json),
    );
    return ApprovalDraftDto.parseDetail(response.data);
  }

  @override
  Future<ApprovalDraftDetail> save(ApprovalDraftSaveInput input) async {
    final payload = input.toJson();
    final response = await _api.post<Map<String, dynamic>>(
      ApiRoutes.approvalDrafts,
      data: payload,
      options: Options(responseType: ResponseType.json),
    );
    final detail = ApprovalDraftDto.parseDetail(response.data);
    if (detail == null) {
      throw const FormatException('초안 저장 응답이 비어 있습니다.');
    }
    return detail;
  }

  @override
  Future<void> delete({required int id, required int requesterId}) async {
    final query = ApiClient.buildQuery(filters: {'requester_id': requesterId});
    await _api.delete<void>(
      ApiClient.buildPath(ApiRoutes.approvalDrafts, [id]),
      query: query,
      options: Options(responseType: ResponseType.json),
    );
  }
}
