<?php

namespace Tests\Feature\Api\V1\Support;

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

class SupportControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_index_requires_auth(): void
    {
        $response = $this->getJson('/api/v1/support');

        $response->assertStatus(401);
    }

    public function test_index_returns_requests(): void
    {
        $user = $this->createUser('parent');
        Sanctum::actingAs($user);

        SupportRequest::query()->create([
            'user_id' => $user->id,
            'subject' => 'Help',
            'message' => 'Need assistance',
            'status' => 'open',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

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

        $response->assertOk();
        $response->assertJsonPath('data.requests.0.subject', 'Help');
    }

    public function test_store_validation(): void
    {
        $user = $this->createUser('parent');
        Sanctum::actingAs($user);

        $response = $this->postJson('/api/v1/support', [
            'subject' => 'Hi',
        ]);

        $response->assertStatus(422);
    }

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

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

        $response = $this->postJson('/api/v1/support', [
            'subject' => 'Help',
            'message' => 'Need assistance please',
        ]);

        $response->assertStatus(201);
        $this->assertDatabaseHas('support_requests', [
            'user_id' => $user->id,
            'subject' => 'Help',
        ]);
    }

    private function createUser(string $roleName): User
    {
        $roleId = DB::table('roles')->insertGetId([
            'name' => $roleName,
            'priority' => 1,
            'is_active' => 1,
        ]);

        $user = User::query()->create([
            'firstname' => 'Test',
            'lastname' => 'User',
            'email' => $roleName . '@example.com',
            'cellphone' => '5555555555',
            'address_street' => '123 Main',
            'city' => 'City',
            'state' => 'ST',
            'zip' => '12345',
            'accept_school_policy' => 1,
            'status' => 'Active',
            'password' => bcrypt('secret'),
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        DB::table('user_roles')->insert([
            'user_id' => $user->id,
            'role_id' => $roleId,
        ]);

        return $user;
    }
}
