<?php

namespace Tests\Feature\Api\V1\Auth;

use App\Models\Role;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Tests\TestCase;

class RegisterControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_captcha_endpoint_returns_value(): void
    {
        $response = $this->getJson('/api/v1/auth/register/captcha');

        $response->assertOk();
        $response->assertJsonStructure(['ok', 'captcha']);
        $this->assertNotEmpty($response->json('captcha'));
    }

    public function test_register_creates_user(): void
    {
        Mail::fake();

        DB::table('configuration')->insert([
            ['id' => 2001, 'config_key' => 'school_year', 'config_value' => '2025-2026'],
            ['id' => 2002, 'config_key' => 'semester', 'config_value' => 'Fall'],
        ]);

        Role::query()->create([
            'id' => 1,
            'name' => 'parent',
            'slug' => 'parent',
            'description' => 'Parent',
            'priority' => 1,
            'is_active' => 1,
        ]);

        $payload = [
            'firstname' => 'Parent',
            'lastname' => 'User',
            'gender' => 'Male',
            'email' => 'parent@example.com',
            'confirm_email' => 'parent@example.com',
            'cellphone' => '5555555555',
            'address_street' => '123 Main',
            'apt' => 'A',
            'city' => 'City',
            'state' => 'CT',
            'zip' => '12345',
            'accept_school_policy' => 1,
            'captcha' => 'ABCD',
            'is_parent' => 1,
            'no_second_parent_info' => 1,
        ];

        $response = $this->withSession(['captcha_answer' => 'ABCD'])
            ->postJson('/api/v1/auth/register', $payload);

        $response->assertCreated();
        $response->assertJsonPath('ok', true);

        $this->assertDatabaseHas('users', [
            'email' => 'parent@example.com',
            'status' => 'Inactive',
        ]);
    }
}
