import { test } from '@japa/runner'
import { MatchUserRoleAccessRule } from '../../../../src/modeling/rules/MatchUserRole.js'

test.group('MatchUserRoleAccessRule', () => {
  test('initializes with default values', ({ assert }) => {
    const rule = new MatchUserRoleAccessRule()
    assert.equal(rule.type, 'matchUserRole')
    assert.deepEqual(rule.role, [])
  }).tags(['@modeling', '@rule', '@match-user-role'])

  test('initializes with provided values', ({ assert }) => {
    const role = ['admin', 'manager']
    const rule = new MatchUserRoleAccessRule({ role })

    assert.equal(rule.type, 'matchUserRole')
    assert.deepEqual(rule.role, role)
  }).tags(['@modeling', '@rule', '@match-user-role'])

  test('constructor copies arrays (immutability)', ({ assert }) => {
    const role = ['admin']
    const rule = new MatchUserRoleAccessRule({ role })

    // Modify original source
    role.push('guest')

    assert.deepEqual(rule.role, ['admin'])
  }).tags(['@modeling', '@rule', '@match-user-role', '@immutability'])

  test('toJSON returns valid schema', ({ assert }) => {
    const rule = new MatchUserRoleAccessRule({ role: ['admin'] })
    const json = rule.toJSON()

    // Modify JSON
    json.role.push('guest')

    assert.equal(json.type, 'matchUserRole')
    assert.lengthOf(rule.role, 1) // Ensure immutability
    assert.equal(rule.role[0], 'admin')
  }).tags(['@modeling', '@rule', '@match-user-role', '@serialization', '@immutability'])

  test('notifies change when role changes', async ({ assert }) => {
    const rule = new MatchUserRoleAccessRule()
    let notified = false
    rule.addEventListener('change', () => {
      notified = true
    })

    rule.role = ['admin']
    await Promise.resolve()
    assert.isTrue(notified)
  }).tags(['@modeling', '@rule', '@match-user-role', '@observed'])
})
