<?php

namespace Tests\Feature\Console;

use App\Enums\TenantAnnouncementAudience;
use App\Enums\TenantAnnouncementDeliveryStatus;
use App\Enums\TenantAnnouncementStatus;
use App\Models\Tenant;
use App\Models\TenantAnnouncement;
use App\Models\TenantAnnouncementDelivery;
use App\Models\User;
use App\Notifications\TenantAnnouncementNotification;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Notification;
use Tests\TestCase;

class DispatchTenantAnnouncementsCommandTest extends TestCase
{
    use RefreshDatabase;

    public function test_dispatches_email_notifications_for_active_announcements(): void
    {
        Notification::fake();

        $tenant = Tenant::factory()->create(['contact_email' => 'owner@example.com']);
        $user = User::factory()->create(['tenant_id' => $tenant->id]);
        $tenant->user()->associate($user)->save();

        $announcement = TenantAnnouncement::factory()->create([
            'status' => TenantAnnouncementStatus::ACTIVE,
            'audience' => TenantAnnouncementAudience::ALL,
            'email_enabled' => true,
        ]);

        $this->artisan('tenant-announcements:dispatch')->assertExitCode(0);

        Notification::assertSentOnDemand(
            TenantAnnouncementNotification::class,
            function (TenantAnnouncementNotification $notification, array $channels, $notifiable) use ($announcement, $tenant): bool {
                $payload = $notification->toArray($notifiable);

                return in_array('mail', $channels, true)
                    && $payload['announcement_id'] === $announcement->id
                    && $payload['tenant_id'] === $tenant->id;
            }
        );

        $this->assertTrue(TenantAnnouncementDelivery::query()
            ->where('tenant_announcement_id', $announcement->id)
            ->where('tenant_id', $tenant->id)
            ->where('channel', 'mail')
            ->where('status', TenantAnnouncementDeliveryStatus::QUEUED)
            ->exists());
    }
}
