<?php

namespace Tests\Feature\Api\V1\Whatsapp;

use App\Events\WhatsappInvitesSend;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

class WhatsappInviteControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_parent_contacts_endpoint_returns_contacts(): void
    {
        $user = $this->createUser();
        Sanctum::actingAs($user);

        DB::table('parents')->insert([
            'secondparent_firstname' => 'Parent',
            'secondparent_lastname' => 'Two',
            'secondparent_email' => 'parent2@example.com',
            'secondparent_phone' => '5555555555',
            'firstparent_id' => 10,
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $response = $this->getJson('/api/v1/whatsapp/parent-contacts?school_year=2025-2026&semester=Fall');

        $response->assertOk();
        $response->assertJsonPath('status', true);
        $this->assertNotEmpty($response->json('data.contacts'));
    }

    public function test_parent_contacts_by_class_endpoint_returns_sections(): void
    {
        $user = $this->createUser();
        Sanctum::actingAs($user);

        $this->seedInviteData();

        $response = $this->getJson('/api/v1/whatsapp/parent-contacts-by-class?school_year=2025-2026');

        $response->assertOk();
        $response->assertJsonPath('status', true);
        $this->assertNotEmpty($response->json('data.class_sections'));
    }

    public function test_send_invites_returns_success_when_listener_registered(): void
    {
        $user = $this->createUser();
        Sanctum::actingAs($user);

        $this->seedInviteData();
        Event::listen(WhatsappInvitesSend::class, static function () {
        });

        $response = $this->postJson('/api/v1/whatsapp/invites/send', [
            'mode' => 'parents',
            'parent_ids' => [10],
            'school_year' => '2025-2026',
            'semester' => 'Fall',
        ]);

        $response->assertOk();
        $response->assertJsonPath('status', true);
        $this->assertGreaterThanOrEqual(1, (int) $response->json('data.triggered'));
    }

    public function test_send_invites_returns_error_when_no_listener(): void
    {
        $user = $this->createUser();
        Sanctum::actingAs($user);

        $this->seedInviteData();

        $response = $this->postJson('/api/v1/whatsapp/invites/send', [
            'mode' => 'parents',
            'parent_ids' => [10],
            'school_year' => '2025-2026',
            'semester' => 'Fall',
        ]);

        $response->assertStatus(422);
        $response->assertJsonPath('status', false);
    }

    public function test_membership_update_saves_record(): void
    {
        $user = $this->createUser();
        Sanctum::actingAs($user);

        $this->seedInviteData();

        $response = $this->postJson('/api/v1/whatsapp/membership', [
            'class_section_id' => 200,
            'primary_id' => 10,
            'primary_member' => true,
            'school_year' => '2025-2026',
            'semester' => 'Fall',
        ]);

        $response->assertOk();
        $response->assertJsonPath('status', true);
        $this->assertDatabaseHas('whatsapp_group_memberships', [
            'class_section_id' => 200,
            'subject_type' => 'primary',
            'subject_id' => 10,
            'is_member' => 1,
        ]);
    }

    public function test_send_invites_validation_rejects_payload(): void
    {
        $user = $this->createUser();
        Sanctum::actingAs($user);

        $response = $this->postJson('/api/v1/whatsapp/invites/send', [
            'mode' => 'parents',
        ]);

        $response->assertStatus(422);
        $response->assertJsonPath('message', 'Validation failed.');
    }

    private function seedInviteData(): void
    {
        DB::table('classSection')->insert([
            'class_section_id' => 200,
            'class_section_name' => 'Grade 1',
            'class_id' => 1,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        DB::table('students')->insert([
            'id' => 100,
            'school_id' => 1,
            'firstname' => 'Student',
            'lastname' => 'One',
            'parent_id' => 10,
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'is_active' => 1,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        DB::table('student_class')->insert([
            'student_id' => 100,
            'class_section_id' => 200,
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'is_event_only' => 0,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        DB::table('whatsapp_group_links')->insert([
            'class_section_id' => 200,
            'class_section_name' => 'Grade 1',
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'invite_link' => 'https://chat.whatsapp.com/abc',
            'active' => 1,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        DB::table('parents')->insert([
            'secondparent_firstname' => 'Parent',
            'secondparent_lastname' => 'Two',
            'secondparent_email' => 'parent2@example.com',
            'secondparent_phone' => '5555555555',
            'firstparent_id' => 10,
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

    private function createUser(): User
    {
        DB::table('users')->insert([
            'id' => 10,
            'school_id' => 1,
            'firstname' => 'Parent',
            'lastname' => 'One',
            'cellphone' => '5555555555',
            'email' => 'parent1@example.com',
            'address_street' => '123 Main',
            'city' => 'City',
            'state' => 'ST',
            'zip' => '12345',
            'accept_school_policy' => 1,
            'is_verified' => 1,
            'status' => 'Active',
            'is_suspended' => 0,
            'failed_attempts' => 0,
            'password' => bcrypt('secret'),
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        return User::query()->findOrFail(10);
    }
}
