<?php

namespace Tests\Feature\Api\V1\System;

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

class SchoolIdControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_generate_student_returns_id(): void
    {
        $user = User::factory()->create();
        Sanctum::actingAs($user);

        $response = $this->getJson('/api/v1/system/school-ids/student');

        $response->assertOk();
        $response->assertJson(['ok' => true]);
        $response->assertJsonPath('result.type', 'student');
        $this->assertNotEmpty($response->json('result.school_id'));
    }

    public function test_generate_user_returns_id(): void
    {
        $user = User::factory()->create();
        Sanctum::actingAs($user);

        $response = $this->getJson('/api/v1/system/school-ids/user');

        $response->assertOk();
        $response->assertJson(['ok' => true]);
        $response->assertJsonPath('result.type', 'user');
        $this->assertNotEmpty($response->json('result.school_id'));
    }

    public function test_assign_sets_user_school_id(): void
    {
        $user = User::factory()->create();
        Sanctum::actingAs($user);

        $target = User::factory()->create([
            'school_id' => null,
        ]);

        $response = $this->postJson('/api/v1/system/school-ids/assign', [
            'user_id' => $target->id,
        ]);

        $response->assertOk();
        $response->assertJson(['ok' => true]);
        $this->assertNotEmpty($response->json('result.school_id'));
        $this->assertSame(
            $response->json('result.school_id'),
            User::query()->findOrFail($target->id)->school_id
        );
    }
}
