<?php

require __DIR__.'/vendor/autoload.php';

$app = require_once __DIR__.'/bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$kernel->bootstrap();

use App\Models\Announcement;
use App\Models\User;

try {
    // Create user if none
    $user = User::first();
    if (! $user) {
        $user = User::factory()->create();
    }

    echo 'Using user ID: '.$user->id."\n";

    // Use Service to create announcement
    $notificationService = new \App\Services\NotificationService;
    $service = new \App\Services\AnnouncementService($notificationService);

    $announcement = $service->save([
        'title' => 'Test Announcement '.uniqid(),
        'message' => 'Testing target_type = user (Immediate)',
        'attachments' => ['test.jpg'],
        'publish_type' => 'now',
        'target_type' => 'user',
        'user_ids' => [$user->id], // Target the specific user
        'created_by' => $user->id,
    ]);

    echo 'Announcement created with ID: '.$announcement->id."\n";

    // Verify user attachment and notified_at
    $attachedUser = $announcement->users()->find($user->id);
    if ($attachedUser && $announcement->notified_at) {
        echo "SUCCESS: Announcement created, user attached, and notified_at set.\n";
    } else {
        echo "FAILURE: User not attached or notified_at not set.\n";
        if (! $attachedUser) {
            echo "- User not attached\n";
        }
        if (! $announcement->notified_at) {
            echo "- notified_at is null\n";
        }
    }

    // Verify read tracking
    try {
        $service->markAsRead($announcement, $user->id);
        if ($announcement->isReadBy($user)) {
            echo "SUCCESS: Announcement marked as read.\n";
        } else {
            echo "FAILURE: Announcement not marked as read.\n";
        }
    } catch (\Exception $e) {
        echo 'FAILURE: Exception while marking as read: '.$e->getMessage()."\n";
    }

    // Clean up
    $announcement->users()->detach($user->id);
    $announcement->readByUsers()->detach($user->id);
    $announcement->delete();

} catch (\Exception $e) {
    echo 'ERROR: '.$e->getMessage()."\n";
    exit(1);
}
