<?php

namespace Tests\Feature\Api\V1\Family;

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

class FamilyAdminControllerTest extends TestCase
{
    use RefreshDatabase;

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

        Sanctum::actingAs($user);
        $response = $this->getJson('/api/v1/family-admin?student_id=' . $studentId);

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

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

        Sanctum::actingAs($user);
        $response = $this->getJson('/api/v1/family-admin/search?q=Student');

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

    public function test_card_returns_family_details(): void
    {
        $this->seedConfig();
        $user = $this->seedUser(1);
        $studentId = $this->seedStudent(10, $user->id);
        $familyId = $this->seedFamily('FAM-1');
        $this->seedFamilyStudent($familyId, $studentId);
        $this->seedFamilyGuardian($familyId, $user->id);
        $this->seedEmergencyContact($user->id);
        $this->seedInvoice($user->id);
        $this->seedPayment($user->id);

        Sanctum::actingAs($user);
        $response = $this->getJson('/api/v1/family-admin/card?family_id=' . $familyId);

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

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

        $this->mock(FamilyNotificationService::class, function ($mock) {
            $mock->shouldReceive('sendComposeEmail')->once()->andReturn(false);
        });

        Sanctum::actingAs($user);
        $response = $this->postJson('/api/v1/family-admin/compose-email', [
            'recipient' => 'recipient@example.com',
            'subject' => 'Hello',
            'html_message' => '<p>Test</p>',
        ]);

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

    public function test_requires_authentication(): void
    {
        $response = $this->getJson('/api/v1/family-admin');

        $response->assertStatus(401);
    }

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

        Sanctum::actingAs($user);
        $response = $this->postJson('/api/v1/family-admin/compose-email', [
            'subject' => 'Hello',
        ]);

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

    private function seedConfig(): void
    {
        DB::table('configuration')->insert([
            ['config_key' => 'school_year', 'config_value' => '2025-2026'],
            ['config_key' => 'semester', 'config_value' => 'Fall'],
        ]);
    }

    private function seedUser(int $id): User
    {
        DB::table('users')->insert([
            'id' => $id,
            'firstname' => 'Parent',
            'lastname' => 'User',
            'cellphone' => '9999999999',
            'email' => 'parent' . $id . '@example.com',
            '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): void
    {
        DB::table('family_students')->insert([
            'family_id' => $familyId,
            'student_id' => $studentId,
            'is_primary_home' => 1,
            '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(),
        ]);
    }

    private function seedEmergencyContact(int $parentId): void
    {
        DB::table('emergency_contacts')->insert([
            'emergency_contact_name' => 'Contact One',
            'parent_id' => $parentId,
            'cellphone' => '5555555555',
            'email' => 'contact@example.com',
            'relation' => 'Friend',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

    private function seedInvoice(int $parentId): void
    {
        DB::table('invoices')->insert([
            'parent_id' => $parentId,
            'invoice_number' => 'INV-100',
            'status' => 'open',
            'total_amount' => 100,
            'paid_amount' => 0,
            'balance' => 100,
            'issue_date' => now()->toDateString(),
            'due_date' => now()->addDays(10)->toDateString(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

    private function seedPayment(int $parentId): void
    {
        DB::table('payments')->insert([
            'parent_id' => $parentId,
            'invoice_id' => 1,
            'total_amount' => 100,
            'paid_amount' => 50,
            'balance' => 50,
            'number_of_installments' => 1,
            'payment_method' => 'cash',
            'payment_date' => now()->toDateString(),
            'status' => 'completed',
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }
}
