<?php

namespace Tests\Feature\Modules\Segments\ControllersLogic;

use App\Classes\ValueObjects\Constants\RoleTypes;
use App\Models\Segment;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use PHPUnit\Framework\Attributes\Group;
use Spatie\Permission\Models\Permission;
use Tests\TestCase;

#[Group('feature')]
#[Group('segments')]
#[Group('logic')]
#[Group('ok_to_run')]
class UpdateSegmentLogic2Test extends TestCase
{
    /** @var User */
    private $admin;

    /** @var Segment */
    private $segment;

    protected function setUp(): void
    {
        parent::setUp();

        // A R R A N G E
        // Create an admin user for authentication
        $email = 'admin_update_segment_execution@example.com';
        $this->admin = User::where('email', $email)->first();
        if (!$this->admin) {
            $this->admin = new User();
            $this->admin->email = $email;
            $this->admin->name = 'Admin Update Segment Execution';
            $this->admin->password = Hash::make('password');
            $this->admin->type = RoleTypes::ADMIN;
            $this->admin->status = 1;
            $this->admin->save();
        }

        // Grant permission to resolve 403 Forbidden
        $permission = Permission::firstOrCreate(['name' => 'edit segment', 'guard_name' => 'api']);
        $this->admin->givePermissionTo($permission);

        // Create a test segment
        $this->segment = new Segment();
        $this->segment->name = 'Update Segment Execution Segment';
        $this->segment->save();
    }

    /**
     * Test updating a segment without Mockery.
     *
     * @return void
     */
    public function test_it_can_update_segment()
    {
        // A R R A N G E
        $newName = 'Updated Segment Name';

        $payload = [
            'name' => $newName
        ];

        // A C T
        $response = $this->actingAs($this->admin, 'api')
            ->putJson("/api/v1/segment/update/{$this->segment->id}", $payload);

        // A S S E R T
        $response->assertStatus(200);
        $response->assertJsonPath('payload.data.name', $newName);

        $this->assertDatabaseHas('segments', [
            'id' => $this->segment->id,
            'name' => $newName
        ]);
    }
}
