<?php

namespace Tests\Unit\Modules\Segments\Services;

use App\Classes\Modules\Segments\Services\FetchesConstant;
use App\Models\Segment;
use App\Models\SegmentConstant;
use App\Classes\Exceptions\ResourceNotFoundException;
use PHPUnit\Framework\Attributes\Group;
use Tests\TestCase;

#[Group('unit')]
#[Group('segments')]
#[Group('services')]
#[Group('ok_to_run')]
class FetchesConstantTest extends TestCase
{
    // use DatabaseTransactions;

    /**
     * Test it can fetch a segment constant by ID.
     *
     * @return void
     */
    public function test_it_can_fetch_a_segment_constant_by_id()
    {
        // A R R A N G E
        $segment = new Segment();
        $segment->name = 'test_it_can_fetch_a_segment_constant_by_id_SEG';
        $segment->save();

        $constant = new SegmentConstant();
        $constant->segment_id = $segment->id;
        $constant->name = 'test_it_can_fetch_a_segment_constant_by_id_CON';
        $constant->reference = 'test_it_can_fetch_a_segment_constant_by_id_REF';
        $constant->detail = (object) ['foo' => 'bar'];
        $constant->save();

        $service = new FetchesConstant(new SegmentConstant());

        // A C T
        $result = $service->execute(['id' => $constant->id]);

        // A S S E R T
        $this->assertInstanceOf(SegmentConstant::class, $result);
        $this->assertEquals($constant->id, $result->id);
    }

    /**
     * Test it can fetch a segment constant by reference.
     *
     * @return void
     */
    public function test_it_can_fetch_a_segment_constant_by_reference()
    {
        // A R R A N G E
        $segment = new Segment();
        $segment->name = 'test_it_can_fetch_a_segment_constant_by_reference_SEG';
        $segment->save();

        $constant = new SegmentConstant();
        $constant->segment_id = $segment->id;
        $constant->name = 'test_it_can_fetch_a_segment_constant_by_reference_CON';
        $constant->reference = 'test_it_can_fetch_a_segment_constant_by_reference_REF';
        $constant->detail = (object) ['foo' => 'bar'];
        $constant->save();

        $service = new FetchesConstant(new SegmentConstant());

        // A C T
        $result = $service->execute(['reference' => 'test_it_can_fetch_a_segment_constant_by_reference_REF']);

        // A S S E R T
        $this->assertInstanceOf(SegmentConstant::class, $result);
        $this->assertEquals($constant->id, $result->id);
    }

    /**
     * Test it throws exception if constant not found.
     *
     * @return void
     */
    public function test_it_throws_exception_if_constant_not_found()
    {
        // A R R A N G E
        $service = new FetchesConstant(new SegmentConstant());

        // A S S E R T
        $this->expectException(ResourceNotFoundException::class);

        // A C T
        $service->execute(['id' => 99999]);
    }
}
