<?php

namespace Tests\Feature\Api\V1\Messaging;

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

class MessagesControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_inbox_requires_auth(): void
    {
        $response = $this->getJson('/api/v1/messages/inbox');

        $response->assertStatus(401);
    }

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

        $sender = $this->createUser('parent', 'sender@example.com');
        $recipient = $this->createUser('teacher', 'recipient@example.com');
        Sanctum::actingAs($sender);

        $payload = [
            'recipient_id' => $recipient->id,
            'subject' => 'Hello',
            'message' => 'Test message',
        ];

        $response = $this->postJson('/api/v1/messages', $payload);

        $response->assertStatus(201);
        $this->assertDatabaseHas('messages', [
            'sender_id' => $sender->id,
            'recipient_id' => $recipient->id,
            'subject' => 'Hello',
        ]);
    }

    public function test_show_marks_read(): void
    {
        $sender = $this->createUser('parent', 'sender2@example.com');
        $recipient = $this->createUser('teacher', 'recipient2@example.com');

        $message = Message::query()->create([
            'sender_id' => $sender->id,
            'recipient_id' => $recipient->id,
            'subject' => 'Subject',
            'message' => 'Body',
            'sent_datetime' => now(),
            'read_status' => 0,
            'message_number' => 'MSG-123',
            'priority' => 'normal',
            'status' => 'sent',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        Sanctum::actingAs($recipient);

        $response = $this->getJson('/api/v1/messages/' . $message->id);

        $response->assertOk();
        $this->assertDatabaseHas('messages', [
            'id' => $message->id,
            'read_status' => 1,
        ]);
    }

    public function test_update_changes_status(): void
    {
        $sender = $this->createUser('parent', 'sender3@example.com');
        $recipient = $this->createUser('teacher', 'recipient3@example.com');

        $message = Message::query()->create([
            'sender_id' => $sender->id,
            'recipient_id' => $recipient->id,
            'subject' => 'Subject',
            'message' => 'Body',
            'sent_datetime' => now(),
            'read_status' => 0,
            'message_number' => 'MSG-124',
            'priority' => 'normal',
            'status' => 'sent',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        Sanctum::actingAs($sender);

        $response = $this->patchJson('/api/v1/messages/' . $message->id, [
            'status' => 'trashed',
        ]);

        $response->assertOk();
        $this->assertDatabaseHas('messages', [
            'id' => $message->id,
            'status' => 'trashed',
        ]);
    }

    public function test_destroy_marks_trashed(): void
    {
        $sender = $this->createUser('parent', 'sender4@example.com');
        $recipient = $this->createUser('teacher', 'recipient4@example.com');

        $message = Message::query()->create([
            'sender_id' => $sender->id,
            'recipient_id' => $recipient->id,
            'subject' => 'Subject',
            'message' => 'Body',
            'sent_datetime' => now(),
            'read_status' => 0,
            'message_number' => 'MSG-125',
            'priority' => 'normal',
            'status' => 'sent',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        Sanctum::actingAs($sender);

        $response = $this->deleteJson('/api/v1/messages/' . $message->id);

        $response->assertOk();
        $this->assertDatabaseHas('messages', [
            'id' => $message->id,
            'status' => 'trashed',
        ]);
    }

    public function test_recipients_teacher_returns_list(): void
    {
        $teacher = $this->createUser('teacher', 'teacher@example.com');
        Sanctum::actingAs($teacher);

        DB::table('teacher_class')->insert([
            'teacher_id' => $teacher->id,
            'class_section_id' => 1,
            'position' => 'main',
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $response = $this->getJson('/api/v1/messages/recipients/teacher');

        $response->assertOk();
        $response->assertJsonPath('data.recipients.0.id', $teacher->id);
    }

    public function test_validation_rejects_missing_subject(): void
    {
        $sender = $this->createUser('parent', 'sender5@example.com');
        $recipient = $this->createUser('teacher', 'recipient5@example.com');
        Sanctum::actingAs($sender);

        $response = $this->postJson('/api/v1/messages', [
            'recipient_id' => $recipient->id,
            'message' => 'Body',
        ]);

        $response->assertStatus(422);
        $response->assertJsonStructure(['message', 'errors']);
    }

    public function test_show_forbidden_for_other_users(): void
    {
        $sender = $this->createUser('parent', 'sender6@example.com');
        $recipient = $this->createUser('teacher', 'recipient6@example.com');
        $other = $this->createUser('student', 'other@example.com');

        $message = Message::query()->create([
            'sender_id' => $sender->id,
            'recipient_id' => $recipient->id,
            'subject' => 'Subject',
            'message' => 'Body',
            'sent_datetime' => now(),
            'read_status' => 0,
            'message_number' => 'MSG-126',
            'priority' => 'normal',
            'status' => 'sent',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        Sanctum::actingAs($other);

        $response = $this->getJson('/api/v1/messages/' . $message->id);

        $response->assertForbidden();
    }

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

        $user = User::query()->create([
            'firstname' => 'Test',
            'lastname' => 'User',
            'email' => $email,
            '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;
    }
}
