<?php

namespace Tests\Unit\Services\Messaging;

use App\Models\User;
use App\Services\Messaging\MessageCommandService;
use App\Services\System\GlobalConfigService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class MessageCommandServiceTest extends TestCase
{
    use RefreshDatabase;

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

        $sender = $this->createUser('sender@example.com');
        $recipient = $this->createUser('recipient@example.com');

        $service = new MessageCommandService(new GlobalConfigService());
        $message = $service->create($sender->id, [
            'recipient_id' => $recipient->id,
            'subject' => 'Subject',
            'message' => 'Body',
        ]);

        $this->assertNotNull($message->id);
        $this->assertDatabaseHas('messages', [
            'id' => $message->id,
            'subject' => 'Subject',
        ]);
    }

    public function test_create_rejects_invalid_role(): void
    {
        $sender = $this->createUser('sender2@example.com');

        $service = new MessageCommandService(new GlobalConfigService());

        $this->expectException(\RuntimeException::class);
        $service->create($sender->id, [
            'recipient_role' => 'invalid',
            'subject' => 'Subject',
            'message' => 'Body',
        ]);
    }

    private function createUser(string $email): User
    {
        return 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',
        ]);
    }
}
