import 'package:flutter_test/flutter_test.dart';
import 'package:nomadcode_app/src/integrations/proto_socket/proto_socket_envelope.dart';

void main() {
  test('ProtoSocketEnvelope round-trips through google.protobuf.Struct', () {
    const envelope = ProtoSocketEnvelope(
      id: 'msg-1',
      correlationId: 'corr-1',
      type: 'request',
      channel: 'task',
      action: 'task.list',
      actor: {'kind': 'client', 'id': 'apps/client'},
      auth: {'scheme': 'basic', 'token_ref': 'runtime-secret-ref'},
      payload: {
        'limit': 20,
        'include_archived': false,
        'tags': ['core', 'client'],
        'filter': {'source': 'manual', 'empty': null},
      },
      meta: {'connection_id': 'conn-1'},
    );

    final roundTrip = ProtoSocketEnvelope.fromStruct(envelope.toStruct());

    expect(roundTrip.protocolVersion, equals(protoSocketProtocolVersion));
    expect(roundTrip.id, equals('msg-1'));
    expect(roundTrip.correlationId, equals('corr-1'));
    expect(roundTrip.type, equals('request'));
    expect(roundTrip.channel, equals('task'));
    expect(roundTrip.action, equals('task.list'));
    expect(roundTrip.actor, equals(envelope.actor));
    expect(roundTrip.auth, equals(envelope.auth));
    expect(roundTrip.payload['limit'], equals(20.0));
    expect(roundTrip.payload['include_archived'], isFalse);
    expect(roundTrip.payload['tags'], equals(['core', 'client']));
    expect(
      roundTrip.payload['filter'],
      equals({'source': 'manual', 'empty': null}),
    );
    expect(roundTrip.meta, equals(envelope.meta));
  });

  test('error envelope preserves retryable and details', () {
    const envelope = ProtoSocketEnvelope(
      id: 'err-1',
      correlationId: 'req-1',
      type: 'error',
      channel: 'task',
      action: 'task.get',
      error: ProtoSocketEnvelopeError(
        code: 'task.not_found',
        message: 'task not found',
        retryable: false,
        details: {'id': 'task-404', 'attempts': 2},
      ),
    );

    final roundTrip = ProtoSocketEnvelope.fromStruct(envelope.toStruct());

    expect(roundTrip.error, isNotNull);
    expect(roundTrip.error!.code, equals('task.not_found'));
    expect(roundTrip.error!.message, equals('task not found'));
    expect(roundTrip.error!.retryable, isFalse);
    expect(
      roundTrip.error!.details,
      equals({'id': 'task-404', 'attempts': 2.0}),
    );
  });
}
