<?php

namespace App\Notifications;

use App\Models\User;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\DB;

class WeeklyDigestNotification extends Notification
{
    public array $stats;

    public function __construct(public User $creator)
    {
        $videoIds = $creator->videos()->pluck('id');

        $views = DB::table('video_views')
            ->whereIn('video_id', $videoIds)
            ->where('created_at', '>=', now()->subWeek())
            ->count();

        $likes = DB::table('video_likes')
            ->whereIn('video_id', $videoIds)
            ->where('created_at', '>=', now()->subWeek())
            ->count();

        $newSubs = DB::table('user_subscriptions')
            ->where('channel_id', $creator->id)
            ->where('created_at', '>=', now()->subWeek())
            ->count();

        $topVideo = $creator->videos()
            ->withCount(['viewers as week_views' => fn($q) => $q->where('video_views.created_at', '>=', now()->subWeek())])
            ->orderByDesc('week_views')
            ->first();

        $this->stats = [
            'views'     => $views,
            'likes'     => $likes,
            'new_subs'  => $newSubs,
            'top_video' => $topVideo,
        ];
    }

    public function via(object $notifiable): array
    {
        return $notifiable->notificationPref('email_weekly_digest') ? ['mail'] : [];
    }

    public function toMail(object $notifiable): MailMessage
    {
        return (new MailMessage)
            ->subject('Your weekly TAKEONE summary 📊')
            ->view('emails.weekly-digest', [
                'creator'   => $this->creator,
                'stats'     => $this->stats,
            ]);
    }
}
