<?php

declare(strict_types=1);

namespace App\Domain\Ai\Jobs;

use App\Contracts\LlmProvider;
use App\Models\Comment;
use App\Settings\AiSettings;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Log;

class ModerateCommentJob implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public int $commentId,
    ) {
        $this->onQueue('ai-moderation');
    }

    public function handle(LlmProvider $llm, AiSettings $settings): void
    {
        if (! $settings->comment_moderation_enabled) {
            return;
        }

        $comment = Comment::query()->find($this->commentId);

        if ($comment === null) {
            return;
        }

        if ($comment->moderation_status !== Comment::STATUS_PENDING_AI) {
            $comment->update(['moderation_status' => Comment::STATUS_PENDING_AI]);
        }

        try {
            $result = $llm->moderate($comment->content);
            $status = match ($result['status'] ?? 'needs_human') {
                'approved' => Comment::STATUS_APPROVED,
                'rejected' => Comment::STATUS_REJECTED,
                default => Comment::STATUS_NEEDS_HUMAN,
            };

            $comment->forceFill([
                'moderation_status' => $status,
                'published_at' => $status === Comment::STATUS_APPROVED
                    ? ($comment->published_at ?? now())
                    : $comment->published_at,
            ])->save();
        } catch (\Throwable $exception) {
            Log::warning('Comment moderation failed.', [
                'comment_id' => $this->commentId,
                'message' => $exception->getMessage(),
            ]);

            $comment->update(['moderation_status' => Comment::STATUS_NEEDS_HUMAN]);
        }
    }
}
