<?php

namespace Tests\Unit\Services\Whatsapp;

use App\Services\Whatsapp\WhatsappContextService;
use App\Services\Whatsapp\WhatsappLinkService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class WhatsappLinkServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_upsert_creates_link(): void
    {
        $service = new WhatsappLinkService(new WhatsappContextService());

        $link = $service->upsert([
            'class_section_id' => 300,
            'class_section_name' => 'Grade 6',
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'invite_link' => 'https://chat.whatsapp.com/grade6',
            'active' => true,
        ]);

        $this->assertNotEmpty($link->id);
        $this->assertDatabaseHas('whatsapp_group_links', [
            'class_section_id' => 300,
            'invite_link' => 'https://chat.whatsapp.com/grade6',
        ]);
    }

    public function test_paginate_filters_by_active(): void
    {
        DB::table('whatsapp_group_links')->insert([
            [
                'class_section_id' => 301,
                'class_section_name' => 'Grade 7',
                'school_year' => '2025-2026',
                'semester' => 'Fall',
                'invite_link' => 'https://chat.whatsapp.com/a',
                'active' => 1,
                'created_at' => now(),
                'updated_at' => now(),
            ],
            [
                'class_section_id' => 302,
                'class_section_name' => 'Grade 8',
                'school_year' => '2025-2026',
                'semester' => 'Fall',
                'invite_link' => 'https://chat.whatsapp.com/b',
                'active' => 0,
                'created_at' => now(),
                'updated_at' => now(),
            ],
        ]);

        $service = new WhatsappLinkService(new WhatsappContextService());
        $page = $service->paginate(['active' => true]);

        $this->assertCount(1, $page->items());
        $this->assertSame(301, $page->items()[0]->class_section_id);
    }
}
