<?php

namespace Tests\Feature\Api\V1\Workflows;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\Concerns\AssertsE2EApiResponses;
use Tests\Concerns\SeedsE2ETestFixtures;
use Tests\TestCase;

/**
 * Scenario Y: Family, guardians, authorized users, and WhatsApp communications.
 *
 * Family data is deceptively dangerous: one wrong join and someone sees another
 * household. This locks down guardian attachment, flags, contact exports, and
 * authorized-user invitation flows.
 */
class ScenarioYFamilyGuardianAuthorizedUserAndWhatsappLifecycleTest extends TestCase
{
    use RefreshDatabase;
    use SeedsE2ETestFixtures;
    use AssertsE2EApiResponses;

    public function test_admin_builds_family_links_and_manages_guardian_flags(): void
    {
        $world = $this->seedTeacherClassWithStudent();
        $admin = $this->actingAsApiAdministrator();
        $primaryParent = $world['parent'];
        $studentId = $world['student_id'];
        $secondParent = $this->createApiUserWithRole('parent', [
            'firstname' => 'Second',
            'lastname' => 'Guardian',
            'email' => 'second.guardian.' . uniqid('', true) . '@example.test',
        ]);

        $this->actingAs($admin, 'api');

        $bootstrap = $this->postJson('/api/v1/families/bootstrap', [
            'primary_parent_id' => $primaryParent->id,
            'student_ids' => [$studentId],
            'home_name' => 'E2E Household',
        ]);
        $this->assertNoServerError($bootstrap, 'Family bootstrap');

        $familyId = (int) DB::table('families')
            ->where('primary_parent_id', $primaryParent->id)
            ->orWhere('name', 'E2E Household')
            ->value('id');

        if ($familyId > 0) {
            $this->postJson('/api/v1/families/attach-second/by-user', [
                'family_id' => $familyId,
                'user_id' => $secondParent->id,
                'relation' => 'Father',
            ])->assertSuccessful();
            $this->postJson('/api/v1/families/set-primary-home', [
                'family_id' => $familyId,
                'student_id' => $studentId,
            ])->assertSuccessful();
            $this->postJson('/api/v1/families/set-guardian-flags', [
                'family_id' => $familyId,
                'user_id' => $secondParent->id,
                'can_pickup' => true,
                'can_receive_billing' => false,
                'can_receive_academic' => true,
            ])->assertSuccessful();

            $this->getJson('/api/v1/families/' . $familyId . '/guardians')
                ->assertSuccessful();
            $this->getJson('/api/v1/family-admin/card?family_id=' . $familyId)
                ->assertSuccessful();
        }

        $this->getJson('/api/v1/families/by-student/' . $studentId)
            ->assertSuccessful();
        $this->getJson('/api/v1/family-admin/search?q=E2E')
            ->assertSuccessful();
    }

    public function test_parent_authorized_user_invite_and_household_privacy_flow(): void
    {
        $world = $this->seedTeacherClassWithStudent();
        $parent = $world['parent'];
        $admin = $this->actingAsApiAdministrator();
        $this->actingAs($parent, 'api');

        $invite = $this->postJson('/api/v1/parents/authorized-users', [
            'name' => 'E2E Pickup Helper',
            'email' => 'pickup.helper.' . uniqid('', true) . '@example.test',
            'cellphone' => '5554446666',
            'relation' => 'Uncle',
            'permissions' => ['pickup'],
        ]);
        $this->assertNoServerError($invite, 'Authorized user invite creation');

        $authorizedUserId = (int) DB::table('authorized_users')
            ->where('parent_id', $parent->id)
            ->value('id');

        if ($authorizedUserId > 0) {
            $this->getJson('/api/v1/parents/authorized-users')
                ->assertSuccessful();
            $this->patchJson('/api/v1/parents/authorized-users/' . $authorizedUserId, [
                'name' => 'E2E Pickup Helper Updated',
                'cellphone' => '5554447777',
                'relation' => 'Uncle',
                'permissions' => ['pickup', 'emergency'],
            ])->assertSuccessful();
        }

        $this->actingAs($admin, 'api');
        $this->getJson('/api/v1/whatsapp/parent-contacts')
            ->assertSuccessful();
        $this->getJson('/api/v1/whatsapp/parent-contacts-by-class')
            ->assertSuccessful();

        $link = $this->postJson('/api/v1/whatsapp/links', [
            'title' => 'E2E Parent Group',
            'url' => 'https://chat.whatsapp.com/e2e-test-link',
            'audience' => 'parents',
            'class_section_id' => $world['class_section_id'],
            'is_active' => true,
        ]);
        $this->assertSuccessfulOrValidation($link, 'WhatsApp link creation');

        $linkId = (int) DB::table('whatsapp_links')
            ->where('title', 'E2E Parent Group')
            ->value('id');
        if ($linkId > 0) {
            $this->patchJson('/api/v1/whatsapp/links/' . $linkId, [
                'title' => 'E2E Parent Group Updated',
                'url' => 'https://chat.whatsapp.com/e2e-test-link-updated',
                'audience' => 'parents',
                'is_active' => true,
            ])->assertSuccessful();
            $this->postJson('/api/v1/whatsapp/membership', [
                'link_id' => $linkId,
                'parent_id' => $parent->id,
                'status' => 'joined',
            ])->assertSuccessful();
        }
    }
}
