<?php

namespace App\Services\Notifications;

use App\Models\Configuration;
use App\Models\Notification;
use App\Models\UserNotification;

class UserNotificationDispatchService
{
    public function notifyUser(
        int $userId,
        string $title,
        string $message,
        array $channels = ['in_app'],
        string $topic = 'general',
        ?string $targetGroup = null
    ): array {
        if ($userId <= 0) {
            return ['ok' => false, 'message' => 'Invalid user id.'];
        }

        $channels = array_values(array_unique(array_map('strtolower', (array) $channels)));
        if (empty($channels)) {
            $channels = ['in_app'];
        }

        $schoolYear = Configuration::getConfigValueByKey('school_year');
        $semester = Configuration::getConfigValueByKey('semester');

        $notification = Notification::query()->create([
            'title' => $title,
            'message' => $message,
            'target_group' => $targetGroup ?: 'everyone',
            'delivery_channels' => $channels,
            'priority' => 'normal',
            'status' => 'sent',
            'scheduled_at' => now(),
            'sent_at' => now(),
            'school_year' => $schoolYear,
            'semester' => $semester,
        ]);

        UserNotification::query()->create([
            'notification_id' => (int) $notification->id,
            'user_id' => $userId,
            'is_read' => 0,
            'delivered' => in_array('in_app', $channels, true) ? 1 : 0,
            'delivered_at' => in_array('in_app', $channels, true) ? now() : null,
            'school_year' => $schoolYear,
            'semester' => $semester,
        ]);

        return [
            'ok' => true,
            'notification_id' => (int) $notification->id,
            'topic' => $topic,
        ];
    }
}
