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

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

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

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

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

    const action = new ReadAction({
      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', '@read-action', '@immutability'])

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

    const json = action.toJSON()

    assert.equal(json.kind, 'read')
    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', '@read-action', '@serialization'])

  test('notifies change when inherited property changes', async ({ assert }) => {
    const action = new ReadAction()
    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', '@read-action', '@observed'])

  test('notifies change when accessRule value change', async ({ assert }) => {
    const action = new ReadAction()
    let notified = false
    action.addEventListener('change', () => {
      notified = true
    })

    action.accessRule.push(new AccessRule({ type: 'allowPublic' }))
    await Promise.resolve()
    assert.isTrue(notified)
  }).tags(['@modeling', '@action', '@read-action', '@observed'])
})
