<?php

namespace Tests\Feature\Modules\Segments\ControllersLogic;

use App\Classes\Modules\Segments\ControllersLogic\FetchConstantLogic;
use App\Classes\Modules\Segments\Services\FetchesConstant;
use App\Models\SegmentConstant;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Bus;
use App\Classes\Jobs\UserRiskAnalysis;
use PHPUnit\Framework\Attributes\Group;
use Tests\TestCase;
use Mockery;

#[Group('feature')]
#[Group('segments')]
#[Group('logic')]
#[Group('ok_to_run')]
class FetchConstantLogicTest extends TestCase
{

    // use DatabaseTransactions;

    /**
     * Test FetchConstantLogic execution.
     *
     * @return void
     */
    public function test_fetch_constant_logic_execution()
    {
        // A R R A N G E
        Bus::fake([UserRiskAnalysis::class]);

        $email = 'test_fetch_constant_logic_execution@example.com';
        $user = User::where('email', $email)->first();
        if (!$user) {
            $user = new User();
            $user->name = 'test_fetch_constant_logic_execution';
            $user->email = $email;
            $user->password = bcrypt('password');
            $user->save();
        }
        $this->actingAs($user);

        $constant = new SegmentConstant();
        $constant->id = 1;
        $constant->name = 'test_fetch_constant_logic_execution';
        $constant->reference = 'test_fetch_constant_logic_execution';
        $constant->detail = (object) ['foo' => 'bar'];

        // Mock FetchesConstant
        $fetchesConstant = Mockery::mock(FetchesConstant::class);
        $fetchesConstant->shouldReceive('execute')
            ->once()
            ->with(['segment_id' => 1, 'reference' => 'test_fetch_constant_logic_execution'])
            ->andReturn($constant);

        $logic = new FetchConstantLogic($fetchesConstant);

        $request = Request::create('/api/segments/1/constants/test_fetch_constant_logic_execution', 'GET');
        $request->headers->set('captcha-token', 'fake-token');
        $request->setRouteResolver(function () {
            $route = Mockery::mock(\Illuminate\Routing\Route::class);
            $route->shouldReceive('parameter')->with('id', null)->andReturn(1);
            $route->shouldReceive('parameter')->with('reference', null)->andReturn('test_fetch_constant_logic_execution');
            return $route;
        });

        // A C T
        $response = $logic->execute($request);

        // A S S E R T
        $this->assertEquals(200, $response->getStatusCode());
        $data = $response->getData(true);
        $this->assertEquals('Fetch Segment Constant Successful', $data['title']);
        $this->assertEquals('test_fetch_constant_logic_execution', $data['payload']['data']['reference']);
    }

    protected function tearDown(): void
    {
        Mockery::close();
        parent::tearDown();
    }
}
