<?php

namespace Tests\Feature\Api\V1\System;

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

class SemesterRangeControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_school_year_range_uses_config_dates(): void
    {
        $user = $this->seedUser();
        Sanctum::actingAs($user);

        DB::table('configuration')->insert([
            ['id' => 1, 'config_key' => 'fall_semester_start', 'config_value' => '2025-09-05'],
            ['id' => 2, 'config_key' => 'last_school_day', 'config_value' => '2026-06-15'],
        ]);

        $response = $this->getJson('/api/v1/system/semester-range/school-year?school_year=2025-2026');

        $response->assertOk();
        $response->assertJsonPath('range.start_date', '2025-09-05');
        $response->assertJsonPath('range.end_date', '2026-06-15');
    }

    public function test_resolve_returns_semester_for_date(): void
    {
        $user = $this->seedUser();
        Sanctum::actingAs($user);

        DB::table('configuration')->insert([
            ['id' => 1, 'config_key' => 'fall_semester_start', 'config_value' => '2025-09-01'],
            ['id' => 2, 'config_key' => 'spring_semester_start', 'config_value' => '2026-01-20'],
            ['id' => 3, 'config_key' => 'last_school_day', 'config_value' => '2026-06-01'],
        ]);

        $response = $this->getJson('/api/v1/system/semester-range/resolve?date=2025-10-01');

        $response->assertOk();
        $response->assertJsonPath('resolution.semester', 'Fall');
    }

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