// Copyright (c) 2024, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:developer';

import 'package:test/test.dart';
import 'package:vm_service/vm_service.dart';
import 'package:vm_service/vm_service_io.dart';

import 'common/service_test_common.dart';

// AUTOGENERATED START
//
// Update these constants by running:
//
// dart pkg/vm_service/test/update_line_numbers.dart pkg/vm_service/test/id_zone_deletion_on_client_disconnect_common.dart
//
const LINE_A = 25;
// AUTOGENERATED END

void testeeMain() {
  // ignore: unused_local_variable
  final abcString = 'abc';
  debugger(); // LINE_A
}

final idZoneDeletionOnDisconnectTests = <IsolateTest>[
  hasStoppedAtBreakpoint,
  stoppedAtLine(LINE_A),
  (VmService client1, IsolateRef isolateRef) async {
    final isolateId = isolateRef.id!;

    final idZone1 = await client1.createIdZone(
      isolateId,
      IdZoneBackingBufferKind.kRing,
      IdAssignmentPolicy.kAlwaysAllocate,
    );

    // Confirm that [idZone1] can be used.
    await client1.evaluateInFrame(
      isolateId,
      0,
      'abcString',
      idZoneId: idZone1.id,
    );

    final client2 = await vmServiceConnectUri(client1.wsUri!);
    final idZone2 = await client2.createIdZone(
      isolateId,
      IdZoneBackingBufferKind.kRing,
      IdAssignmentPolicy.kAlwaysAllocate,
    );

    // Confirm that [idZone2] can be used.
    await client2.evaluateInFrame(
      isolateId,
      0,
      'abcString',
      idZoneId: idZone2.id,
    );

    // Disposing of [client2] should delete [idZone2];
    await client2.dispose();

    // Confirm that [idZone2] can be no longer be used.
    try {
      await client1.evaluateInFrame(
        isolateId,
        0,
        'abcString',
        idZoneId: idZone2.id,
      );
      fail('successfully used an ID zone that should have been deleted');
    } on RPCError catch (e) {
      expect(e.code, RPCErrorKind.kInvalidParams.code);
    }

    // Confirm that [idZone1] can still be used.
    await client1.evaluateInFrame(
      isolateId,
      0,
      'abcString',
      idZoneId: idZone1.id,
    );
  },
];
