<?php

namespace Tests\Feature\Api\V1\Communication;

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

class CommunicationControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_options_returns_students_and_templates(): void
    {
        $this->seedCommunicationData();

        $user = $this->createUser();
        Sanctum::actingAs($user);

        $response = $this->getJson('/api/v1/communications/options');

        $response->assertOk();
        $this->assertNotEmpty($response->json('students'));
        $this->assertNotEmpty($response->json('templates'));
    }

    public function test_preview_returns_rendered_subject_and_body(): void
    {
        $this->seedCommunicationData();

        $user = $this->createUser();
        Sanctum::actingAs($user);

        $response = $this->postJson('/api/v1/communications/preview', [
            'template_key' => 'welcome',
            'student_id' => 1,
            'family_id' => 1,
            'vars' => ['custom' => 'value'],
        ]);

        $response->assertOk();
        $this->assertStringContainsString('Parent One', (string) $response->json('subject'));
        $this->assertStringContainsString('Student One', (string) $response->json('html'));
    }

    public function test_send_dispatches_email(): void
    {
        $this->seedCommunicationData();

        $fake = new class extends EmailService {
            public array $sent = [];

            public function send(
                array|string $to,
                string $subject,
                string $html,
                string $fromKey = 'general',
                array $cc = [],
                array $bcc = []
            ): bool {
                $this->sent[] = compact('to', 'subject', 'html', 'fromKey', 'cc', 'bcc');
                return true;
            }
        };

        $this->app->instance(EmailService::class, $fake);

        $user = $this->createUser();
        Sanctum::actingAs($user);

        $response = $this->postJson('/api/v1/communications/send', [
            'student_id' => 1,
            'family_id' => 1,
            'template_key' => 'welcome',
            'subject' => 'Hello',
            'body' => '<p>Hi</p>',
            'recipients' => ['parent1@example.com'],
            'cc' => ['parent2@example.com'],
        ]);

        $response->assertOk();
        $response->assertJson(['ok' => true]);
        $this->assertCount(1, $fake->sent);
    }

    private function seedCommunicationData(): void
    {
        DB::table('students')->insert([
            'id' => 1,
            'school_id' => 'S-1',
            'firstname' => 'Student',
            'lastname' => 'One',
            'age' => 8,
            'gender' => 'Male',
            'photo_consent' => 1,
            'parent_id' => 1,
            'year_of_registration' => '2025',
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'is_active' => 1,
            'is_new' => 0,
            'registration_grade' => '1-A',
        ]);

        DB::table('families')->insert([
            'id' => 1,
            'family_code' => 'F-1',
            'household_name' => 'Family One',
            'is_active' => 1,
        ]);

        DB::table('family_students')->insert([
            'family_id' => 1,
            'student_id' => 1,
            'is_primary_home' => 1,
        ]);

        DB::table('users')->insert([
            'id' => 2,
            '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',
        ]);

        DB::table('family_guardians')->insert([
            'family_id' => 1,
            'user_id' => 2,
            'relation' => 'parent',
            'is_primary' => 1,
            'receive_emails' => 1,
            'receive_sms' => 0,
        ]);

        DB::table('email_templates')->insert([
            'id' => 1,
            'code' => 'welcome',
            'variant' => 'default',
            'subject' => 'Hello {{parent_salutation}}',
            'body_html' => 'Hi {{student_fullname}}',
            'is_active' => 1,
        ]);
    }

    private function createUser(): User
    {
        DB::table('users')->insert([
            'id' => 1,
            'school_id' => 1,
            'firstname' => 'Admin',
            'lastname' => 'User',
            'cellphone' => '5555555555',
            'email' => 'admin@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(1);
    }
}
