<?php

namespace Tests\Feature\Api;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\Concerns\CreatesApiTestUsers;
use Tests\TestCase;

class ApiAttendanceTemplateFeatureTest extends TestCase
{
    use CreatesApiTestUsers;
    use RefreshDatabase;

    public function test_attendance_comment_templates_can_be_managed_through_current_api(): void
    {
        $this->actingAsApiAdministrator();

        $create = $this->postJson('/api/v1/attendance-comment-templates', [
            'min_score' => 0,
            'max_score' => 59,
            'template_text' => 'Needs follow up with parent.',
            'is_active' => true,
        ])
            ->assertCreated()
            ->assertJsonPath('status', 'success');

        $id = (int) data_get($create->json(), 'data.id');
        $this->assertGreaterThan(0, $id);

        $this->getJson('/api/v1/attendance-comment-templates')
            ->assertOk()
            ->assertJsonPath('status', 'success')
            ->assertJsonFragment(['template_text' => 'Needs follow up with parent.']);

        $this->getJson("/api/v1/attendance-comment-templates/$id")
            ->assertOk()
            ->assertJsonPath('data.id', $id);

        $this->putJson("/api/v1/attendance-comment-templates/$id", [
            'max_score' => 60,
            'template_text' => 'Updated follow up text.',
        ])
            ->assertOk()
            ->assertJsonPath('status', 'success');

        $this->deleteJson("/api/v1/attendance-comment-templates/$id")
            ->assertOk()
            ->assertJsonPath('status', 'success');
    }

    public function test_attendance_comment_template_validation_blocks_bad_ranges(): void
    {
        $this->actingAsApiAdministrator();

        $this->postJson('/api/v1/attendance-comment-templates', [
            'min_score' => 90,
            'max_score' => 10,
            'template_text' => '',
        ])
            ->assertStatus(422)
            ->assertJsonValidationErrors(['max_score', 'template_text']);
    }

    public function test_legacy_attendance_template_aliases_still_work(): void
    {
        $this->actingAsApiAdministrator();

        $this->postJson('/api/v1/attendance-templates/save', [
            'min_score' => 70,
            'max_score' => 80,
            'template_text' => 'Legacy alias text.',
            'is_active' => 'on',
        ])
            ->assertOk()
            ->assertJsonPath('status', 'success');

        $list = $this->getJson('/api/v1/attendance-templates')
            ->assertOk()
            ->assertJsonFragment(['template_text' => 'Legacy alias text.']);

        $id = (int) collect($list->json('templates'))->firstWhere('template_text', 'Legacy alias text.')['id'];

        $this->postJson('/api/v1/attendance-templates/delete', ['id' => $id])
            ->assertOk()
            ->assertJsonPath('status', 'success');
    }
}
