<?php

namespace AuthStack\Driver\tests\units\Collection;

use AuthStack\Driver\Errors\NonexistentKeyError;
use mageekguy\atoum;
use Illuminate\Support\Collection;
use AuthStack\TwoFactor\Model\Key;
use AuthStack\Driver\Model\SecurityKey;
use AuthStack\Driver\Collection\TwoFactorKeys as KeyCollection;

class TwoFactorKeys extends atoum
{
    public function testCreatePasses()
    {
        $this
            ->given($collection = new KeyCollection())
            ->then
                ->object($key = SecurityKey::findOrFail(1))->isInstanceOf(SecurityKey::class)
                ->object($collection->add($key->toKey()))->isInstanceOf(KeyCollection::class)
                ->boolean($collection->has(1))->isTrue()
                ->object($collection->getById(1))->isInstanceOf(Key::class)
                ->array($collection->getU2FKeyIds())->isNotEmpty()
                ->integer($collection->size())->isEqualTo(1)
                ->integer($collection->count(KeyCollection::TYPE_U2F))->isEqualTo(1)
                ->integer($collection->count(KeyCollection::TYPE_OTP))->isEqualTo(0)
                ->boolean($collection->hasU2F())->isTrue()
                ->array($collection->filter(KeyCollection::TYPE_U2F))->isNotEmpty()
                ->array($collection->filter(KeyCollection::TYPE_OTP))->isEmpty()
                ->array($collection->all())->isNotEmpty()
                ->object($collection->toArray())->isInstanceOf(Collection::class)

        ;
    }

    public function testCreateFromArray()
    {
        $this
            ->given($key = SecurityKey::findOrFail(1))
            ->and($data = [], $data[] = $key->toArray())
            ->then
                ->object($collection = KeyCollection::fromArray($data))->isInstanceOf(KeyCollection::class)
                ->integer($collection->size())->isEqualTo(1)
            ;
    }

    public function testCreateFromMultipleRecords()
    {
        $this
            ->given($keys = SecurityKey::all())
            ->then
                ->object($keys)->isInstanceOf(\Illuminate\Database\Eloquent\Collection::class)
                ->array($keys->toArray())->isNotEmpty()
                ->object($collection = KeyCollection::fromArray($keys->toArray()))->isInstanceOf(KeyCollection::class)
        ;
    }

    public function testThrowsErrorForNonexistentKey()
    {
        $this
            ->given($key = SecurityKey::findOrFail(1))
            ->and($data = [], $data[] = $key->toArray())
            ->then
            ->object($collection = KeyCollection::fromArray($data))->isInstanceOf(KeyCollection::class)
            ->exception(function () use ($collection) {
                $collection->getById(123456);
            })
                ->isInstanceOf(NonexistentKeyError::class)
                ->hasMessage('No such key associated with user: 123456')
        ;
    }
}
