import { test } from '@japa/runner'
import { Provider, IProvider, Kind as ProviderKind } from '../../../src/models/Provider.js'

test.group('Models > Provider > constructor()', () => {
  test('creates a default instance', ({ assert }) => {
    const result = new Provider()
    assert.equal(result.kind, ProviderKind)
    assert.isUndefined(result.url)
    assert.isUndefined(result.name)
    assert.isUndefined(result.email)
  })

  test('creates an instance from a schema', ({ assert }) => {
    const init: IProvider = {
      kind: ProviderKind,
      name: 'test name',
      url: 'https://dot.com',
      email: 'a@b.c',
    }
    const result = new Provider(init)
    assert.equal(result.kind, ProviderKind)
    assert.equal(result.url, init.url)
    assert.equal(result.name, init.name)
    assert.equal(result.email, init.email)
  })

  test('creates an instance from a JSON schema string', ({ assert }) => {
    const init: IProvider = {
      kind: ProviderKind,
      name: 'test name',
      url: 'https://dot.com',
      email: 'a@b.c',
    }
    const result = new Provider(JSON.stringify(init))
    assert.equal(result.kind, ProviderKind)
    assert.equal(result.url, init.url)
    assert.equal(result.name, init.name)
    assert.equal(result.email, init.email)
  })
})

test.group('Models > Provider > new()', (group) => {
  let instance: Provider
  group.each.setup(() => {
    instance = new Provider()
  })

  test('throws when invalid schema', ({ assert }) => {
    assert.throws(() => {
      // @ts-expect-error Used in testing
      instance.new({})
    })
  })

  test('sets the URL', ({ assert }) => {
    const schema = instance.toJSON()
    schema.url = 'https://dot.com'
    instance.new(schema)
    assert.equal(instance.url, 'https://dot.com')
  })

  test('sets the name', ({ assert }) => {
    const schema = instance.toJSON()
    schema.name = 'test name'
    instance.new(schema)
    assert.equal(instance.name, 'test name')
  })

  test('sets the email', ({ assert }) => {
    const schema = instance.toJSON()
    schema.email = 'a@b.c'
    instance.new(schema)
    assert.equal(instance.email, 'a@b.c')
  })
})

test.group('Models > Provider > toJSON()', (group) => {
  let instance: Provider
  group.each.setup(() => {
    instance = new Provider()
  })

  const properties: (keyof IProvider)[] = ['url', 'name', 'email']

  test('serializes the kind', ({ assert }) => {
    const result = instance.toJSON()
    assert.equal(result.kind, ProviderKind)
  })

  properties.forEach((prop) => {
    test(`does not serialize the ${prop} when missing`, ({ assert }) => {
      const result = instance.toJSON()
      assert.isUndefined(result[prop])
    })

    test(`serializes the ${prop}`, ({ assert }) => {
      instance[prop] = `test ${prop}`
      const result = instance.toJSON()
      assert.equal(result[prop], `test ${prop}`)
    })
  })
})
