import 'package:http/http.dart' as http;

import '../../../errors/server_exception.dart';
import '../../../http_errors.dart';
import '../../nextcloud_ocs.dart';
import 'get_chat_params.dart';
import 'get_chat_response.dart';

/// Backwards-paging variant of GetChat (`lookIntoFuture=0` + `lastKnownMessageId`)
/// that fetches the page of messages *older* than a given id. Bypasses [TalkApi]
/// because that layer treats non-2xx as errors, and the server answers HTTP 304
/// when there are no older messages left — a normal "start of chat" outcome here.
/// `setReadMarker=off` so paging into history never moves the read cursor.
class GetChatHistory {
  final String chatToken;
  final int lastKnownMessageId;
  final int limit;

  GetChatHistory({
    required this.chatToken,
    required this.lastKnownMessageId,
    required this.limit,
  });

  /// Returns the older page, or `null` on HTTP 304 (no older messages).
  Future<GetChatResponse?> run() async {
    final params = GetChatParams(
      lookIntoFuture: GetChatParamsSwitch.off,
      lastKnownMessageId: lastKnownMessageId,
      includeLastKnown: GetChatParamsSwitch.off,
      setReadMarker: GetChatParamsSwitch.off,
      limit: limit,
    );
    final uri = NextcloudOcs.uri(
      'apps/spreed/api/v1/chat/$chatToken',
      queryParameters: params.toJson(),
    );
    final headers = NextcloudOcs.headers();

    final response = (await sendGuarded(
      'GetChatHistory $uri',
      () => http.get(uri, headers: headers),
    ))!;

    final status = response.statusCode;
    if (status == 304) return null;
    if (status >= 200 && status < 300) {
      return GetChatResponse.fromJson(NextcloudOcs.decode(response.body))
        ..headers = response.headers;
    }
    throw ServerException(
      statusCode: status,
      technicalDetails: 'GetChatHistory $uri: HTTP $status',
    );
  }
}
