<?php

use App\Models\Segment;
use App\Models\User;
use Illuminate\Foundation\Testing\WithFaker;

uses(WithFaker::class);

it('creates a decision with add_segment event when config is valid', function () {
    $user = User::factory()->create([
        'email_verified_at' => now(),
    ]);
    $this->actingAs($user);

    $segment = Segment::factory()->create();

    $addSegmentEventId = \DB::table('events')->insertGetId([
        'name' => 'Add Segment',
        'key' => 'add_segment',
        'description' => 'Attach a segment to contract',
        'active' => 1,
        'config' => json_encode([]),
        'options' => json_encode([]),
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    $payload = [
        'name' => fake()->unique()->words(2, true),
        'color_tag' => null,
        'auto_mail' => false,
        'email_template_id' => null,
        'actions' => [],
        'events' => [
            [
                'id' => $addSegmentEventId,
                'active' => true,
                'run_order' => 1,
                'config' => [
                    'segment_id' => $segment->id,
                    'deactivate_previous' => true,
                ],
            ],
        ],
    ];

    $response = $this->post(route('settings.decisions.store'), $payload);

    $response->assertSessionHasNoErrors();
    $response->assertRedirect(route('settings.workflow'));
});

it('validates segment_id is required for add_segment event on create', function () {
    $user = User::factory()->create([
        'email_verified_at' => now(),
    ]);
    $this->actingAs($user);

    $addSegmentEventId = \DB::table('events')->insertGetId([
        'name' => 'Add Segment',
        'key' => 'add_segment',
        'description' => 'Attach a segment to contract',
        'active' => 1,
        'config' => json_encode([]),
        'options' => json_encode([]),
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    $payload = [
        'name' => fake()->unique()->words(2, true),
        'color_tag' => null,
        'auto_mail' => false,
        'email_template_id' => null,
        'events' => [
            [
                'id' => $addSegmentEventId,
                'active' => true,
                'run_order' => 1,
                'config' => [
                    // missing segment_id
                    'deactivate_previous' => true,
                ],
            ],
        ],
    ];

    $response = $this->post(route('settings.decisions.store'), $payload);

    $response->assertSessionHasErrors(['events.0.config.segment_id']);
});
