<?php

namespace Tests\Feature\Api\V1\Settings;

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

class SchoolCalendarControllerTest extends TestCase
{
    use RefreshDatabase;

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

        $response = $this->getJson('/api/v1/settings/school-calendar/options');

        $response->assertOk();
        $response->assertJsonPath('status', true);
        $this->assertNotEmpty($response->json('data.event_types'));
        $this->assertSame('2025-2026', $response->json('data.defaults.school_year'));
    }

    public function test_index_returns_events_and_meetings(): void
    {
        $this->seedConfig();
        $user = $this->seedUser();
        $this->seedEvent();
        $this->seedMeeting();

        Sanctum::actingAs($user);
        $response = $this->getJson('/api/v1/settings/school-calendar/events?school_year=2025-2026&include_meetings=1');

        $response->assertOk();
        $response->assertJsonPath('status', true);
        $this->assertNotEmpty($response->json('data.events'));
        $this->assertArrayHasKey('backgroundColor', $response->json('data.events.0'));
        $this->assertArrayHasKey('extendedProps', $response->json('data.events.0'));
    }

    public function test_show_returns_event(): void
    {
        $this->seedConfig();
        $user = $this->seedUser();
        $eventId = $this->seedEvent();

        Sanctum::actingAs($user);
        $response = $this->getJson('/api/v1/settings/school-calendar/events/' . $eventId);

        $response->assertOk();
        $response->assertJsonPath('status', true);
        $response->assertJsonPath('data.event.id', $eventId);
    }

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

        $payload = [
            'title' => 'Calendar Event',
            'date' => '2026-01-10',
            'description' => 'Description',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ];

        $response = $this->postJson('/api/v1/settings/school-calendar/events', $payload);

        $response->assertStatus(201);
        $response->assertJsonPath('status', true);
        $this->assertDatabaseHas('calendar_events', [
            'title' => 'Calendar Event',
            'school_year' => '2025-2026',
        ]);
    }

    public function test_update_updates_event(): void
    {
        $this->seedConfig();
        $user = $this->seedUser();
        $eventId = $this->seedEvent();

        Sanctum::actingAs($user);
        $response = $this->patchJson('/api/v1/settings/school-calendar/events/' . $eventId, [
            'title' => 'Updated Event',
        ]);

        $response->assertOk();
        $response->assertJsonPath('status', true);
        $this->assertDatabaseHas('calendar_events', [
            'id' => $eventId,
            'title' => 'Updated Event',
        ]);
    }

    public function test_destroy_deletes_event(): void
    {
        $this->seedConfig();
        $user = $this->seedUser();
        $eventId = $this->seedEvent();

        Sanctum::actingAs($user);
        $response = $this->deleteJson('/api/v1/settings/school-calendar/events/' . $eventId);

        $response->assertOk();
        $response->assertJsonPath('status', true);
        $this->assertDatabaseMissing('calendar_events', ['id' => $eventId]);
    }

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

        $response = $this->postJson('/api/v1/settings/school-calendar/events', [
            'title' => 'No date',
        ]);

        $response->assertStatus(422);
        $response->assertJsonPath('message', 'Validation failed.');
    }

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

        $this->app->bind(\App\Services\Settings\SchoolCalendar\SchoolCalendarMutationService::class, function () {
            return new class {
                public function create(array $payload, array $targets = []): array
                {
                    throw new \RuntimeException('fail');
                }
            };
        });

        $response = $this->postJson('/api/v1/settings/school-calendar/events', [
            'title' => 'Event',
            'date' => '2026-01-10',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        $response->assertStatus(500);
        $response->assertJsonPath('status', false);
    }

    public function test_requires_authentication(): void
    {
        $response = $this->getJson('/api/v1/settings/school-calendar/events');

        $response->assertStatus(401);
    }

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

    private function seedUser(): User
    {
        $userId = DB::table('users')->insertGetId([
            'firstname' => 'Admin',
            'lastname' => 'User',
            'cellphone' => '9999999999',
            'email' => 'calendar@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 seedEvent(): int
    {
        return DB::table('calendar_events')->insertGetId([
            'title' => 'Event',
            'date' => '2026-01-01',
            'description' => 'Desc',
            'notify_parent' => 1,
            'notify_admin' => 0,
            'notify_teacher' => 0,
            'no_school' => 0,
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'notification_sent' => 0,
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

    private function seedMeeting(): void
    {
        DB::table('parent_meeting_schedules')->insert([
            'student_id' => 1,
            'parent_user_id' => 1,
            'parent_name' => 'Parent',
            'student_name' => 'Student',
            'class_section_name' => 'Grade 1',
            'date' => '2026-01-02',
            'time' => '10:00:00',
            'notes' => 'Notes',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'status' => 'scheduled',
            'created_by' => null,
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }
}
