import { mount } from '@vue/test-utils';
import { describe, it, expect } from 'vitest';
import MCheckboxGroup from './MCheckboxGroup.vue';
import MCheckbox from '@/components/checkbox/MCheckbox.vue';

describe('MCheckboxGroup.vue', () => {
  it('renders checkboxes based on options', async () => {
    const options = [
      { id: '1', label: 'Option 1', value: 'option1' },
      { id: '2', label: 'Option 2', value: 'option2' },
    ];

    const wrapper = mount(MCheckboxGroup, {
      props: {
        name: 'test-name',
        options,
      },
    });

    const checkboxes = wrapper.findAllComponents(MCheckbox);
    expect(checkboxes.length).toBe(2);

    expect(checkboxes[0].props('label')).toBe('Option 1');
    expect(checkboxes[1].props('label')).toBe('Option 2');
  });

  it('updates modelValue when a checkbox is checked', async () => {
    const options = [
      { id: '1', label: 'Option 1', value: 'option1' },
      { id: '2', label: 'Option 2', value: 'option2' },
    ];

    const wrapper = mount(MCheckboxGroup, {
      props: {
        name: 'test-name',
        options,
        modelValue: [],
      },
    });

    const checkbox1 = wrapper.findAllComponents(MCheckbox)[0].find('input');
    await checkbox1.setChecked(true);

    expect(wrapper.emitted('update:modelValue')).toBeTruthy();
    expect(wrapper.emitted('update:modelValue')[0]).toEqual([['option1']]);

    const checkbox2 = wrapper.findAllComponents(MCheckbox)[1].find('input');
    await checkbox2.setChecked(true);

    expect(wrapper.emitted('update:modelValue')[1]).toEqual([
      ['option1', 'option2'],
    ]);
  });

  it('syncs with the v-model when initial value is passed', async () => {
    const options = [
      { id: '1', label: 'Option 1', value: 'option1' },
      { id: '2', label: 'Option 2', value: 'option2' },
    ];

    const wrapper = mount(MCheckboxGroup, {
      props: {
        name: 'test-name',
        options,
        modelValue: ['option1'],
      },
    });

    const checkboxes = wrapper.findAllComponents(MCheckbox);
    expect(checkboxes[0].props('modelValue')).toBe(true);
    expect(checkboxes[1].props('modelValue')).toBe(false);

    await wrapper.setProps({ modelValue: ['option2'] });

    expect(checkboxes[0].props('modelValue')).toBe(false);
    expect(checkboxes[1].props('modelValue')).toBe(true);
  });
});
