<?php

namespace Tests\Feature;

use App\Facades\TaxonomyMapper;
use App\Mail\NewUnmappedTaxonomyMail;
use App\Master\Models\VehicleMake;
use App\TaxonomyMap;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Mail;
use Tests\TestCase;
use Tests\UserForTenant;

class TaxonomyMapTest extends TestCase
{
    use RefreshDatabase;
    use UserForTenant;

    protected $tenancy = true;

    public function testSearchExisting()
    {
        $make = VehicleMake::query()->create([
            'name' => 'foo'
        ]);
        TaxonomyMap::query()->create([
            'taxonomy_type' => 'master-make',
            'taxonomy_id' => $make->id,
            'term' => 'foo baz bar',
            'provider' => 'lorem ipsum'
        ]);

        $match = TaxonomyMapper::search('lorem ipsum', 'make', 'foo baz bar');
        $this->assertEquals($make->id, $match);
    }

    public function testSearchMatching()
    {
        $make = VehicleMake::query()->create([
            'name' => 'foo baz bar'
        ]);
        $match = TaxonomyMapper::search('lorem ipsum', 'make', 'foo baz bar');
        $this->assertEquals($make->id, $match);
    }

    public function testSearchNew()
    {
        Mail::fake();
        $match = TaxonomyMapper::search('lorem ipsum', 'make', 'foo baz bar');
        $this->assertNull($match);
    }

    public function testRelationShip()
    {
        $make = VehicleMake::query()->create([
            'name' => 'foo'
        ]);
        $make->refresh();
        $map = TaxonomyMap::query()
            ->create([
                'taxonomy_type' => 'master-make',
                'taxonomy_id' => $make->id,
                'term' => 'foo baz bar',
                'provider' => 'lorem ipsum'
            ]);

        $this->assertTrue($make->is($map->taxonomy));
    }

    public function testAutomaticMapping()
    {
        TaxonomyMap::query()
            ->create([
                'taxonomy_type' => 'master-model',
                'taxonomy_id' => 123,
                'term' => 'foo baz bar',
                'provider' => 'lorem ipsum'
            ]);

        $this->assertCount(1, TaxonomyMap::all());

        $mapped_taxonomy_id = TaxonomyMapper::search('dolor', 'model', 'foo baz bar');

        $this->assertCount(2, TaxonomyMap::all());
        $this->assertEquals(123, $mapped_taxonomy_id);
    }
}
