<?php

namespace Tests\Feature\Api\V1\Email;

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

class EmailExtractorControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_emails_endpoint_returns_users_and_parents(): 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' => 1,
            'secondparent_id' => 2,
            'school_year' => '2025-2026',
        ]);

        $response = $this->getJson('/api/v1/email-extractor/emails');

        $response->assertOk();
        $response->assertJsonPath('ok', true);
        $this->assertContains('parent2@example.com', $response->json('emails.parents'));
    }

    public function test_compare_endpoint_returns_comparison(): 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' => 1,
            'secondparent_id' => 2,
            'school_year' => '2025-2026',
        ]);

        $response = $this->postJson('/api/v1/email-extractor/compare', [
            'csv_emails' => ['parent2@example.com', 'missing@example.com'],
        ]);

        $response->assertOk();
        $response->assertJsonPath('ok', true);
        $this->assertContains('parent2@example.com', $response->json('comparison.existed'));
    }

    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);
    }
}
