<?php

namespace Tests\Feature;

use App\Models\User;
use App\Models\WhatsAppGroup;
use App\Services\WhatsAppService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;

use Livewire\Livewire;
use Tests\TestCase;

class WhatsAppGatewayAntiBlockTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        $this->seed();
    }

    public function test_authenticated_admin_can_access_whatsapp_gateway_page(): void
    {
        $admin = User::where('email', 'admin@smkn1gunungagung.sch.id')->first();
        $admin->update(['force_password_change' => false]);
        $this->actingAs($admin);

        $response = $this->get('/whatsapp-gateway');
        $response->assertStatus(200);
        $response->assertSee('WA Gateway Anti-Block');
        $response->assertSee('Proteksi Keamanan Anti-Block');
        $response->assertSee('Mode Outbound Safe');
    }

    public function test_whatsapp_service_can_send_message_with_anti_block_delay(): void
    {
        Http::fake([
            'https://api.fonnte.com/send' => Http::response([
                'status' => true,
                'detail' => 'Message queued in Fonnte',
            ], 200),
        ]);

        config(['services.whatsapp.token' => 'dummy_token_12345']);

        $service = app(WhatsAppService::class);
        $sent = $service->sendMessage('12036301234567890@g.us', 'Uji Coba Group WA', 'Pesan Uji Coba Keamanan');

        $this->assertTrue($sent);

        Http::assertSent(function ($request) {
            return $request->url() === 'https://api.fonnte.com/send' &&
                $request->hasHeader('Authorization', 'dummy_token_12345') &&
                str_contains($request['message'], 'Uji Coba Group WA');
        });
    }

    public function test_livewire_can_save_group_wa_orang_tua_mapping(): void
    {
        $admin = User::where('email', 'admin@smkn1gunungagung.sch.id')->first();
        $admin->update(['force_password_change' => false]);
        $this->actingAs($admin);

        Livewire::test(\App\Livewire\WhatsApp\WhatsAppGatewayIndex::class)
            ->set('newTargetType', 'class')
            ->set('newClassName', 'X RPL 1')
            ->set('newGroupName', 'Group Paguyuban Orang Tua X RPL 1')
            ->set('newGroupTargetId', '12036309999@g.us')
            ->call('saveGroupMapping')
            ->assertHasNoErrors();

        $this->assertDatabaseHas('whatsapp_groups', [
            'class_name' => 'X RPL 1',
            'group_name' => 'Group Paguyuban Orang Tua X RPL 1',
            'group_target_id' => '12036309999@g.us',
        ]);
    }
}
