import { test } from '@japa/runner'
import { CreateAction } from '../../../../src/modeling/actions/CreateAction.js'
import { AccessRule } from '../../../../src/modeling/rules/index.js'

test.group('CreateAction', () => {
  test('initializes with default values', ({ assert }) => {
    const action = new CreateAction()
    assert.equal(action.kind, 'create')
    assert.isEmpty(action.accessRule) // Inherited from Action
  }).tags(['@modeling', '@action', '@create-action'])

  test('initializes with inherited values', ({ assert }) => {
    const action = new CreateAction({
      accessRule: [{ type: 'allowPublic' }],
    })

    assert.equal(action.kind, 'create')
    assert.lengthOf(action.accessRule, 1)
    assert.equal(action.accessRule[0].type, 'allowPublic')
  }).tags(['@modeling', '@action', '@create-action'])

  test('constructor copies arrays (immutability)', ({ assert }) => {
    const rules = [{ type: 'allowPublic' }]

    const action = new CreateAction({
      accessRule: rules,
    })

    // Modify original source
    rules.push({ type: 'other' })
    rules[0].type = 'changed'

    assert.lengthOf(action.accessRule, 1)
    assert.equal(action.accessRule[0].type, 'allowPublic')
  }).tags(['@modeling', '@action', '@create-action', '@immutability'])

  test('toJSON returns valid schema', ({ assert }) => {
    const action = new CreateAction({
      accessRule: [{ type: 'allowPublic' }],
    })

    const json = action.toJSON()

    assert.equal(json.kind, 'create')
    if (json.accessRule) {
      assert.lengthOf(json.accessRule, 1)
      assert.equal(json.accessRule[0].type, 'allowPublic')
    } else {
      assert.fail('accessRule should be present in JSON')
    }
  }).tags(['@modeling', '@action', '@create-action', '@serialization'])

  test('notifies change when inherited property changes', async ({ assert }) => {
    const action = new CreateAction()
    let notified = false
    action.addEventListener('change', () => {
      notified = true
    })

    // Modify inherited property
    action.accessRule = [new AccessRule({ type: 'allowPublic' })]
    await Promise.resolve()
    assert.isTrue(notified)
  }).tags(['@modeling', '@action', '@create-action', '@observed'])
})
