<?php

namespace Tests\Feature\Api\V1\Subjects;

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

class SubjectCurriculumControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_index_returns_entries(): void
    {
        $user = $this->seedUser();
        $classId = $this->seedClass();
        $this->seedEntry($classId);

        Sanctum::actingAs($user);
        $response = $this->getJson('/api/v1/subjects/curriculum');

        $response->assertOk();
        $response->assertJson(['ok' => true]);
        $this->assertNotEmpty($response->json('entries'));
    }

    public function test_store_creates_entry(): void
    {
        $user = $this->seedUser();
        $classId = $this->seedClass();

        Sanctum::actingAs($user);
        $response = $this->postJson('/api/v1/subjects/curriculum', [
            'class_id' => $classId,
            'subject' => 'islamic',
            'unit_number' => 1,
            'unit_title' => 'Faith',
            'chapter_name' => 'Intro',
        ]);

        $response->assertStatus(201);
        $this->assertDatabaseHas('subject_curriculum_items', [
            'class_id' => $classId,
            'chapter_name' => 'Intro',
        ]);
    }

    private function seedUser(): User
    {
        $userId = DB::table('users')->insertGetId([
            'firstname' => 'Admin',
            'lastname' => 'User',
            'cellphone' => '1111111111',
            'email' => 'curriculum@example.com',
            'address_street' => '123 Street',
            'city' => 'City',
            'state' => 'ST',
            'zip' => '12345',
            'accept_school_policy' => 1,
            'password' => bcrypt('password'),
            'user_type' => 'primary',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'status' => 'Active',
        ]);

        return User::query()->findOrFail($userId);
    }

    private function seedClass(): int
    {
        return DB::table('classes')->insertGetId([
            'class_name' => 'Grade 2',
            'schedule' => 'Sunday',
            'capacity' => 25,
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);
    }

    private function seedEntry(int $classId): void
    {
        DB::table('subject_curriculum_items')->insert([
            'class_id' => $classId,
            'subject' => 'islamic',
            'unit_number' => 1,
            'unit_title' => 'Faith',
            'chapter_name' => 'Intro',
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }
}
