<?php

namespace Tests\Feature;

use Carbon\Carbon;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Mtc\MercuryDataModels\Vehicle;
use Tests\TestCase;

class ConversionTrackingTest extends TestCase
{
    use RefreshDatabase;

    protected $tenancy = true;

    public function testRequestPayload()
    {
        $response = $this->asTenant(tenant())
            ->postJson(route('conversions.track'));
        $response->assertStatus(422);

        $response = $this->asTenant(tenant())
            ->postJson(route('conversions.track'), [
                'id' => 1
            ]);
        $response->assertStatus(422);

        $response = $this->asTenant(tenant())
            ->postJson(route('conversions.track'), [
                'id' => 1,
                'type' => 'foo'
            ]);
        $response->assertStatus(422);

        $response = $this->asTenant(tenant())
            ->postJson(route('conversions.track'), [
                'id' => 1,
                'type' => 'foo',
                'model' => 'baz',
            ]);
        $response->assertStatus(422);

        $vehicle = Vehicle::factory()->create();
        $response = $this->asTenant(tenant())
            ->postJson(route('conversions.track'), [
                'id' => $vehicle->id,
                'type' => 'foo',
                'model' => 'vehicle',
            ]);
        $response->assertStatus(200);
    }

    public function testConversionsTrackedAgainstModel()
    {
        $vehicle = Vehicle::factory()->create();
        $this->assertEquals(0, $vehicle->conversions()->count());
        $response = $this->asTenant(tenant())
            ->postJson(route('conversions.track'), [
                'id' => $vehicle->id,
                'type' => 'foo',
                'model' => 'vehicle',
            ]);
        $response->assertStatus(200);

        $this->assertEquals(1, $vehicle->conversions()->count());
        $this->assertEquals(1, $vehicle->conversions()->count());
        $conversion = $vehicle->conversions()->first();
        $this->assertTrue(Carbon::now()->isSameDay($conversion->date));
        $this->assertEquals(1, $conversion->hits);
        $this->assertEquals('foo', $conversion->type);
    }
}
