<?php

namespace Tests\Feature\Modules\Segments\ControllersLogic;

use App\Classes\Modules\Segments\ControllersLogic\FetchSegmentLogic;
use App\Classes\Modules\Segments\Services\FetchesSegment;
use App\Classes\Modules\Segments\Standards\Rules\CanFetchSegment;
use App\Models\Segment;
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 FetchSegmentLogicTest extends TestCase
{

    // use DatabaseTransactions;

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

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

        $segment = new Segment();
        $segment->id = 1;
        $segment->name = 'test_fetch_segment_logic_execution';

        // Mock CanFetchSegment
        $canFetchSegment = Mockery::mock(CanFetchSegment::class);
        $canFetchSegment->shouldReceive('passes')->once()->andReturn(true);

        // Mock FetchesSegment
        $fetchesSegment = Mockery::mock(FetchesSegment::class);
        $fetchesSegment->shouldReceive('execute')
            ->once()
            ->with(['id' => 1])
            ->andReturn($segment);

        $logic = new FetchSegmentLogic($canFetchSegment, $fetchesSegment);

        $request = Request::create('/api/segments/1', '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);
            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('Retrieved Segment Successful', $data['title']);
        $this->assertEquals('test_fetch_segment_logic_execution', $data['payload']['data']['name']);
    }

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