<?php

namespace Tests\Feature;

use App\Models\Group;
use App\Models\Organisation;
use App\Models\User;
use App\Models\Webhook;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Notification;
use Tests\TestCase;

/**
 * The pipeline isolation lock. The Oculi notification pipeline is an internal beta, and its entire
 * customer-facing gate is one fact: a hook only receives mitigation traffic if it carries the
 * mitigation usage type, and the only way customers mint hooks is HookController::post_hook, whose
 * validator allows `reporting` alone. This test pins that line - if it ever fails, customers can opt
 * themselves into the beta, and that is an isolation breach, not a validation nit.
 */
class HookUsageGateTest extends TestCase
{
    use RefreshDatabase;

    private $user = null;

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

        config([ 'creatia.reporting.encryption_key' => config('creatia.reporting.encryption_key') ?? 'testing-webhook-key-0123456789ab' ]);

        // Hook creation pages Slack about every attempt; keep that off the network.
        Notification::fake();

        $organisation = Organisation::create([ 'id' => 1, 'name' => 'Organisation #1' ]);
        $group = Group::create([ 'name' => 'Testing' ]);

        $this->user = User::create([
            'phone'             => null,
            'password'          => '',
            'group_id'          => $group->id,
            'organisation_id'   => $organisation->id,
            'name'              => 'User #1',
            'email'             => 'creatia+1@globalsecurelayer.com'
        ]);
    }

    /**
     * The mitigation usage is refused outright, and the same request with the allowed usage succeeds -
     * proving the refusal was the gate itself and not a broken fixture.
     */
    public function testCustomersCannotCreateAMitigationUsageHook(): void
    {
        $response = $this->actingAs($this->user)->withoutMiddleware()->postJson('api/hook', [
            'name'          => 'Sneaky Beta Hook',
            'hook'          => 'https://hooks.slack.com/services/T000/B000/XXXX',
            'hook_type'     => 'slack',
            'usage_type'    => 'mitigation'
        ]);

        $this->assertEquals(400, $response->status(), 'The beta gate must refuse the mitigation usage type.');
        $this->assertSame(0, Webhook::count(), 'No hook row may exist for a refused usage.');

        $response = $this->actingAs($this->user)->withoutMiddleware()->postJson('api/hook', [
            'name'          => 'Ordinary Reporting Hook',
            'hook'          => 'https://hooks.slack.com/services/T000/B000/XXXX',
            'hook_type'     => 'slack',
            'usage_type'    => 'reporting'
        ]);

        $this->assertEquals(200, $response->status(), 'The allowed usage must still pass, or this test is proving nothing.');
        $this->assertSame(1, Webhook::count());
    }
}
