import { mount } from '@vue/test-utils';
import { defineComponent, h, inject } from 'vue';

import { expect, it } from 'vitest';

import { provideUploadEditLoading, uploadEditLoadingKey } from './uploadEditLoading';

it('keeps a window busy until all attachment operations finish, with idempotent releases', () => {
  let loading!: ReturnType<typeof provideUploadEditLoading>;
  const finish: (() => void)[] = [];
  const child = defineComponent({
    setup() {
      finish.push(inject(uploadEditLoadingKey)!()!);
      return () => h('div');
    },
  });
  const wrapper = mount(
    defineComponent({
      setup() {
        loading = provideUploadEditLoading();
        return () => h('div', [h(child), h(child)]);
      },
    }),
  );
  try {
    expect(loading.value).toBe(true);
    finish[0]!();
    finish[0]!();
    expect(loading.value).toBe(true);
    finish[1]!();
    expect(loading.value).toBe(false);
  } finally {
    wrapper.unmount();
  }
});
