<?php

namespace App\Commands;

use App\Libraries\NotificationChannels\EmailChannel;
use App\Models\NotificationModel;
use App\Models\NotificationTemplateModel;
use App\Models\UserModel;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;

/**
 * Retries any notification row that was inserted but never got sent_at set
 * (e.g. transient SMTP failure at insert time in NotificationService::send()).
 * Runs every 15 minutes per the deployment guide's cron table.
 */
class NotificationsDigest extends BaseCommand
{
    protected $group       = 'Scheduler';
    protected $name        = 'notifications:digest';
    protected $description = 'Retries sending any notifications that failed to dispatch on first attempt.';

    public function run(array $params)
    {
        $notifications = new NotificationModel();
        $unsent = $notifications->where('sent_at', null)
            ->where('created_at >=', date('Y-m-d H:i:s', strtotime('-24 hours'))) // don't retry indefinitely
            ->where('channel', 'email') // only email is safely retryable here; sms/whatsapp adapters handle their own retry
            ->findAll(100);

        $userModel = new UserModel();
        $templates = new NotificationTemplateModel();
        $emailChannel = new EmailChannel();
        $sent = 0;

        foreach ($unsent as $n) {
            $user = $userModel->find($n['user_id']);
            if (! $user) {
                continue;
            }
            $template = $templates->find_for($n['type'], 'email');
            if (! $template) {
                continue;
            }
            if ($emailChannel->send($user->email, $template['subject'], $template['body'])) {
                $notifications->update($n['id'], ['sent_at' => date('Y-m-d H:i:s')]);
                $sent++;
            }
        }

        CLI::write("Retried {$sent} of " . count($unsent) . " unsent notification(s).", 'green');
    }
}
