<?php

namespace App\Jobs;

use App\Models\ForumPost;
use App\Models\ForumReply;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

// ══════════════════════════════════════════════════════════════════
//  InPractice — NotifyForumReply Job
//  Location: app/Jobs/NotifyForumReply.php
//
//  Runs in the background after a reply is posted.
//  Never runs inside the HTTP request — always queued.
//
//  Logic:
//    - Notifies the POST AUTHOR that someone replied to their question
//    - Does NOT notify if the replier IS the post author
//      (no point notifying yourself)
//    - Does NOT notify if the post author has notify_forum = false
//    - Does NOT notify if the post author's account is inactive
//
//  Bible compliance:
//    - Dispatched to 'notifications' queue — never synchronous
//    - Stores nickname only — never real name
//    - Respects notify_forum user preference
// ══════════════════════════════════════════════════════════════════

class NotifyForumReply implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * How many times to retry if the job fails.
     */
    public int $tries = 3;

    public function __construct(
        private readonly ForumReply $reply,
        private readonly ForumPost  $post
    ) {}

    public function handle(): void
    {
        // Load what we need — reply author nickname, post author
        $reply = $this->reply->load('user:id,nickname');
        $post  = $this->post->load('user:id,nickname,notify_forum,is_active');

        $postAuthor = $post->user;

        // ── Guard: do not notify if replier is the post author ─
        if ($reply->user_id === $post->user_id) {
            return;
        }

        // ── Guard: respect notification preference ─────────────
        if (! $postAuthor->notify_forum || ! $postAuthor->is_active) {
            return;
        }

        // ── Create one notification for the post author ─────────
        DB::table('notifications')->insert([
            'id'               => Str::uuid()->toString(),
            'notifiable_type'  => 'App\\Models\\User',
            'notifiable_id'    => $postAuthor->id,
            'type'             => 'forum_reply',
            'data'             => json_encode([
                'type'       => 'forum_reply',
                'post_id'    => $post->id,
                'post_title' => $post->title,
                'actor'      => $reply->user->nickname,  // nickname only — never real name
                'link'       => '/app/forum/' . $post->id,
            ]),
            'read_at'          => null,
            'created_at'       => now(),
            'updated_at'       => now(),
        ]);
    }
}
