<?php

namespace App\Console\Commands;

use App\Models\User;
use App\Notifications\WeeklyDigestNotification;
use Illuminate\Console\Command;

class SendWeeklyDigest extends Command
{
    protected $signature   = 'digest:weekly';
    protected $description = 'Send weekly activity digest emails to creators who have it enabled';

    public function handle(): void
    {
        $users = User::whereHas('videos')->get();

        $sent = 0;
        foreach ($users as $user) {
            if (! $user->notificationPref('email_weekly_digest')) {
                continue;
            }
            try {
                $user->notify(new WeeklyDigestNotification($user));
                $sent++;
            } catch (\Throwable $e) {
                \Log::error('Weekly digest failed for user ' . $user->id . ': ' . $e->getMessage());
            }
        }

        $this->info("Sent weekly digest to {$sent} users.");
    }
}
