<?php

namespace Tests\Feature\Api\V1\Family;

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

class FamilyControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_families_by_student_returns_families(): void
    {
        $user = $this->seedUser(1);
        $studentId = $this->seedStudent(10, 1);
        $familyId = $this->seedFamily('FAM-1');
        $this->seedFamilyStudent($familyId, $studentId);

        Sanctum::actingAs($user);
        $response = $this->getJson('/api/v1/families/by-student/' . $studentId);

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

    public function test_guardians_by_family_returns_guardians(): void
    {
        $user = $this->seedUser(1);
        $familyId = $this->seedFamily('FAM-1');
        $this->seedFamilyGuardian($familyId, $user->id);

        Sanctum::actingAs($user);
        $response = $this->getJson('/api/v1/families/' . $familyId . '/guardians');

        $response->assertOk();
        $response->assertJsonPath('status', true);
        $this->assertNotEmpty($response->json('data.guardians'));
        $this->assertSame($user->id, $response->json('data.guardians.0.user_id'));
    }

    public function test_bootstrap_creates_family_and_links(): void
    {
        $user = $this->seedUser(1);
        $this->seedStudent(10, $user->id);

        Sanctum::actingAs($user);
        $response = $this->postJson('/api/v1/families/bootstrap', []);

        $response->assertOk();
        $response->assertJsonPath('status', true);
        $this->assertDatabaseHas('families', ['family_code' => 'FAM-1']);
        $this->assertDatabaseHas('family_students', ['student_id' => 10]);
        $this->assertDatabaseHas('family_guardians', ['user_id' => 1]);
    }

    public function test_attach_second_by_user_links_guardian(): void
    {
        $primary = $this->seedUser(1);
        $secondary = $this->seedUser(2, 'secondary@example.com');
        $studentId = $this->seedStudent(10, $primary->id);
        $familyId = $this->seedFamily('FAM-1');
        $this->seedFamilyStudent($familyId, $studentId);

        Sanctum::actingAs($primary);
        $response = $this->postJson('/api/v1/families/attach-second/by-user', [
            'student_id' => $studentId,
            'user_id' => $secondary->id,
            'relation' => 'secondary',
        ]);

        $response->assertOk();
        $this->assertDatabaseHas('family_guardians', [
            'family_id' => $familyId,
            'user_id' => $secondary->id,
        ]);
    }

    public function test_attach_second_by_email_creates_user_and_links(): void
    {
        $primary = $this->seedUser(1);
        $studentId = $this->seedStudent(10, $primary->id);
        $familyId = $this->seedFamily('FAM-1');
        $this->seedFamilyStudent($familyId, $studentId);

        Sanctum::actingAs($primary);
        $response = $this->postJson('/api/v1/families/attach-second/by-email', [
            'student_id' => $studentId,
            'email' => 'newguardian@example.com',
            'firstname' => 'New',
            'lastname' => 'Guardian',
        ]);

        $response->assertOk();
        $this->assertDatabaseHas('users', ['email' => 'newguardian@example.com']);
        $this->assertDatabaseHas('family_guardians', ['family_id' => $familyId]);
    }

    public function test_set_primary_home_updates_record(): void
    {
        $user = $this->seedUser(1);
        $studentId = $this->seedStudent(10, $user->id);
        $familyId = $this->seedFamily('FAM-1');
        $this->seedFamilyStudent($familyId, $studentId, 0);

        Sanctum::actingAs($user);
        $response = $this->postJson('/api/v1/families/set-primary-home', [
            'family_id' => $familyId,
            'student_id' => $studentId,
            'is_primary_home' => true,
        ]);

        $response->assertOk();
        $this->assertDatabaseHas('family_students', [
            'family_id' => $familyId,
            'student_id' => $studentId,
            'is_primary_home' => 1,
        ]);
    }

    public function test_set_guardian_flags_updates_record(): void
    {
        $user = $this->seedUser(1);
        $familyId = $this->seedFamily('FAM-1');
        $this->seedFamilyGuardian($familyId, $user->id);

        Sanctum::actingAs($user);
        $response = $this->postJson('/api/v1/families/set-guardian-flags', [
            'family_id' => $familyId,
            'user_id' => $user->id,
            'receive_emails' => false,
            'is_primary' => true,
        ]);

        $response->assertOk();
        $this->assertDatabaseHas('family_guardians', [
            'family_id' => $familyId,
            'user_id' => $user->id,
            'receive_emails' => 0,
            'is_primary' => 1,
        ]);
    }

    public function test_set_guardian_flags_requires_payload(): void
    {
        $user = $this->seedUser(1);
        $familyId = $this->seedFamily('FAM-1');
        $this->seedFamilyGuardian($familyId, $user->id);

        Sanctum::actingAs($user);
        $response = $this->postJson('/api/v1/families/set-guardian-flags', [
            'family_id' => $familyId,
            'user_id' => $user->id,
        ]);

        $response->assertStatus(422);
    }

    public function test_unlink_guardian_removes_record(): void
    {
        $user = $this->seedUser(1);
        $familyId = $this->seedFamily('FAM-1');
        $this->seedFamilyGuardian($familyId, $user->id);

        Sanctum::actingAs($user);
        $response = $this->postJson('/api/v1/families/unlink-guardian', [
            'family_id' => $familyId,
            'user_id' => $user->id,
        ]);

        $response->assertOk();
        $this->assertDatabaseMissing('family_guardians', [
            'family_id' => $familyId,
            'user_id' => $user->id,
        ]);
    }

    public function test_unlink_student_removes_record(): void
    {
        $user = $this->seedUser(1);
        $studentId = $this->seedStudent(10, $user->id);
        $familyId = $this->seedFamily('FAM-1');
        $this->seedFamilyStudent($familyId, $studentId);

        Sanctum::actingAs($user);
        $response = $this->postJson('/api/v1/families/unlink-student', [
            'family_id' => $familyId,
            'student_id' => $studentId,
        ]);

        $response->assertOk();
        $this->assertDatabaseMissing('family_students', [
            'family_id' => $familyId,
            'student_id' => $studentId,
        ]);
    }

    public function test_import_legacy_second_parents_links_guardian(): void
    {
        $primary = $this->seedUser(1);
        $this->seedStudent(10, $primary->id);

        DB::table('parents')->insert([
            'firstparent_id' => $primary->id,
            'secondparent_id' => 0,
            'secondparent_email' => 'legacy@example.com',
            'secondparent_firstname' => 'Legacy',
            'secondparent_lastname' => 'Guardian',
            'secondparent_phone' => '5555555555',
            'school_year' => '2025-2026',
        ]);

        Sanctum::actingAs($primary);
        $response = $this->postJson('/api/v1/families/import-legacy-second-parents', []);

        $response->assertOk();
        $this->assertDatabaseHas('family_guardians', [
            'family_id' => 1,
        ]);
        $this->assertDatabaseHas('users', [
            'email' => 'legacy@example.com',
        ]);
    }

    public function test_requires_authentication(): void
    {
        $response = $this->getJson('/api/v1/families/by-student/1');

        $response->assertStatus(401);
    }

    public function test_attach_second_by_user_validation_fails(): void
    {
        $user = $this->seedUser(1);

        Sanctum::actingAs($user);
        $response = $this->postJson('/api/v1/families/attach-second/by-user', [
            'user_id' => 2,
        ]);

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

    private function seedUser(int $id, string $email = 'parent@example.com'): User
    {
        DB::table('users')->insert([
            'id' => $id,
            'firstname' => 'Parent',
            'lastname' => 'User',
            'cellphone' => '9999999999',
            'email' => $email,
            'address_street' => '123 Street',
            'city' => 'City',
            'state' => 'ST',
            'zip' => '12345',
            'accept_school_policy' => 1,
            'password' => bcrypt('password'),
            'user_type' => 'primary',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'status' => 'Active',
        ]);

        return User::query()->findOrFail($id);
    }

    private function seedStudent(int $id, int $parentId): int
    {
        DB::table('students')->insert([
            'id' => $id,
            'school_id' => 'SCH1',
            'firstname' => 'Student',
            'lastname' => 'One',
            'age' => 10,
            'gender' => 'Male',
            'photo_consent' => 1,
            'parent_id' => $parentId,
            'year_of_registration' => '2025-2026',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'is_active' => 1,
        ]);

        return $id;
    }

    private function seedFamily(string $code): int
    {
        return DB::table('families')->insertGetId([
            'family_code' => $code,
            'household_name' => 'Family ' . $code,
            'is_active' => 1,
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

    private function seedFamilyStudent(int $familyId, int $studentId, int $primary = 1): void
    {
        DB::table('family_students')->insert([
            'family_id' => $familyId,
            'student_id' => $studentId,
            'is_primary_home' => $primary,
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

    private function seedFamilyGuardian(int $familyId, int $userId): void
    {
        DB::table('family_guardians')->insert([
            'family_id' => $familyId,
            'user_id' => $userId,
            'relation' => 'primary',
            'is_primary' => 1,
            'receive_emails' => 1,
            'receive_sms' => 0,
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }
}
