<?php

namespace Tests\Feature\Api\Resources;

use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\User;
use App\Customer;

class CustomerControllerTest extends TestCase
{
    use DatabaseTransactions;

    protected $adminToken;
    protected $factory;

    /**
    * A basic test example.
    *
    * @return void
    */
    public function setUp()
    {
       parent::setUp();
       $this->app->make(\Spatie\Permission\PermissionRegistrar::class)->registerPermissions();
       $admin = factory(User::class)->create();
       $admin->assignRole('Admin');
       $this->adminToken = \JWTAuth::fromUser($admin);
       $this->factory = factory(Customer::class)->make()->toArray();
    }

    public function testGETAll()
    {
       $this->withHeaders([
               'Authorization' => 'Bearer '.$this->adminToken,
           ])
           ->json(
               'GET',
               '/api/customers'
           )
           ->assertStatus(200)
           ->assertHeader('Content-Type', 'application/json');
    }

    public function testPOST()
    {
        $factory = $this->factory;
        // $factory['password'] = 'secret';

        $response = $this->withHeaders([
                'Authorization' => 'Bearer '.$this->adminToken,
            ])
            ->json(
                'POST',
                '/api/customers',
                $factory
            )
            ->assertStatus(201)
            ->assertHeader('Content-Type', 'application/json');

        $json = json_decode($response->getContent());
        $factory['id'] = $json->id;

        $response->assertJson($factory);

        $this->assertDatabaseHas('customers', [
            'contact' => $factory['contact'],
        ]);
    }

    public function testDELETE()
    {
        $customer = factory(Customer::class)->create();

        $this->withHeaders([
                'Authorization' => 'Bearer '.$this->adminToken,
            ])
            ->json(
                'DELETE',
                '/api/customers/'.$customer->id
            )
            ->assertStatus(204);

        $this->assertDatabaseMissing('customers', [ 'contact' => $customer->contact ]);
    }


    public function testDisallowAccessToGuestUser()
    {
        $this->json(
                'GET',
                '/api/customers'
            )
            ->assertStatus(401)
            ->assertHeader('Content-Type', 'application/json')
            ->assertJson([
                'message' => __('errors.unauthorized'),
                'message' => 'Token not provided',
            ]);
    }
}
