<?php

declare(strict_types=1);

use App\Filament\Resources\AlertDestinationResource;
use App\Filament\Resources\AlertDestinationResource\Pages\CreateAlertDestination;
use App\Filament\Resources\AlertDestinationResource\Pages\EditAlertDestination;
use App\Models\AlertDestination;
use Livewire\Livewire;

it('creates teams and email destinations, hides secrets, and allows edit/disable', function (): void {
    [$user] = createUserWithTenant(role: 'owner');

    $this->actingAs($user);

    Livewire::test(CreateAlertDestination::class)
        ->fillForm([
            'name' => 'Ops Teams',
            'type' => 'teams_webhook',
            'is_enabled' => true,
            'teams_webhook_url' => 'https://example.invalid/teams-webhook',
        ])
        ->call('create')
        ->assertHasNoFormErrors();

    Livewire::test(CreateAlertDestination::class)
        ->fillForm([
            'name' => 'Ops Email',
            'type' => 'email',
            'is_enabled' => true,
            'email_recipients' => ['ops@example.com', 'oncall@example.com'],
        ])
        ->call('create')
        ->assertHasNoFormErrors();

    expect(AlertDestination::query()->count())->toBe(2);

    $teams = AlertDestination::query()->where('name', 'Ops Teams')->first();
    $email = AlertDestination::query()->where('name', 'Ops Email')->first();

    expect($teams)->not->toBeNull();
    expect($email)->not->toBeNull();

    expect($teams->config['webhook_url'] ?? null)->toBe('https://example.invalid/teams-webhook');
    expect($email->config['recipients'] ?? null)->toBe(['ops@example.com', 'oncall@example.com']);

    expect(array_key_exists('config', $teams->toArray()))->toBeFalse();
    expect(array_key_exists('config', $email->toArray()))->toBeFalse();

    $this->get(AlertDestinationResource::getUrl('edit', ['record' => $teams], panel: 'admin'))
        ->assertOk()
        ->assertDontSee('https://example.invalid/teams-webhook');

    Livewire::test(EditAlertDestination::class, ['record' => $teams->getRouteKey()])
        ->fillForm([
            'name' => 'Ops Teams Updated',
            'is_enabled' => false,
            'teams_webhook_url' => '',
        ])
        ->call('save')
        ->assertHasNoFormErrors();

    $teams->refresh();

    expect($teams->name)->toBe('Ops Teams Updated');
    expect((bool) $teams->is_enabled)->toBeFalse();
});
