import { test } from '@japa/runner'
import { Folder, FolderKind, IFolder, ThingKind } from '../../../../src/index.js'

test.group('Folder.fromName()', () => {
  test('sets the kind', ({ assert }) => {
    const result = Folder.fromName('name')
    assert.equal(result.kind, FolderKind)
  })

  test('sets the name', ({ assert }) => {
    const result = Folder.fromName('name')
    assert.equal(result.info.name, 'name')
  })
})

test.group('Folder.constructor()', () => {
  test('creates a default Folder', ({ assert }) => {
    const result = new Folder()
    assert.equal(result.kind, FolderKind)
    assert.typeOf(result.key, 'string')
    assert.typeOf(result.lastModified, 'object')
  })

  test('creates a Folder from the schema values', ({ assert }) => {
    const schema: IFolder = {
      kind: FolderKind,
      info: {
        kind: ThingKind,
        name: 'hello',
        description: 'a desc',
      },
      key: '123',
      parents: ['p1'],
      permissionIds: ['pr1'],
      permissions: [
        {
          addingUser: '123',
          key: '123',
          kind: 'Core#Permission',
          granteeId: '345',
          role: 'commenter',
          type: 'organization',
          itemId: '678',
          depth: 0,
          sourceRule: 'creator_default_owner',
        },
      ],
      lastModified: { byMe: false, time: 0, user: 'id', name: 'test' },
      labels: ['l1'],
    }
    const result = new Folder(schema)
    assert.equal(result.kind, FolderKind)
    assert.equal(result.info.name, 'hello')
    assert.equal(result.key, '123')
    assert.deepEqual(result.parents, ['p1'])
    assert.deepEqual(result.permissionIds, ['pr1'])
    assert.typeOf(result.permissions, 'array')
    assert.deepEqual(result.lastModified, schema.lastModified)
    assert.deepEqual(result.labels, ['l1'])
  })

  test('creates a Folder from the JSON schema string', ({ assert }) => {
    const schema: IFolder = {
      kind: FolderKind,
      info: {
        kind: ThingKind,
        name: 'hello',
        description: 'a desc',
      },
      key: '123',
      parents: ['p1'],
      permissionIds: ['pr1'],
      permissions: [
        {
          addingUser: '123',
          key: '123',
          kind: 'Core#Permission',
          granteeId: '345',
          role: 'commenter',
          type: 'organization',
          itemId: '678',
          depth: 0,
          sourceRule: 'creator_default_owner',
        },
      ],
      lastModified: { byMe: false, time: 0, user: 'id', name: 'test' },
    }
    const result = new Folder(JSON.stringify(schema))
    assert.equal(result.kind, FolderKind)
    assert.equal(result.info.name, 'hello')
    assert.equal(result.key, '123')
    assert.deepEqual(result.lastModified, schema.lastModified)
  })

  test('throws when invalid schema', ({ assert }) => {
    assert.throws(() => {
      new Folder(
        JSON.stringify({
          name: 'a name',
        })
      )
    })
  })
})
