<?php

namespace App\Actions;

use App\Enums\ApprovalStatusEnum;
use App\Models\Article;
use App\Models\Keyword;
use App\Models\Route;
use App\Models\RouteArticle;
use App\Models\Setting;
use Illuminate\Support\Collection;

class CreateRouteArticlesAction
{
    public function execute(Article $article, string $content): void
    {
        $activeRoutes = Route::where('feed_id', $article->feed_id)
            ->where('is_active', true)
            ->get();

        foreach ($activeRoutes as $route) {
            $this->createForRoute($article, $route, $content);
        }
    }

    public function createForRoute(Article $article, Route $route, string $content): void
    {
        $routeKeywords = Keyword::where('feed_id', $route->feed_id)
            ->where('platform_channel_id', $route->platform_channel_id)
            ->where('is_active', true)
            ->get();

        // Match keywords against full article content, title, and description
        $searchableContent = $content.' '.$article->title.' '.$article->description;
        $status = $this->evaluateKeywords($routeKeywords, $searchableContent);

        if ($status === ApprovalStatusEnum::PENDING && $this->shouldAutoApprove($route)) {
            $status = ApprovalStatusEnum::APPROVED;
        }

        RouteArticle::firstOrCreate(
            [
                'feed_id' => $route->feed_id,
                'platform_channel_id' => $route->platform_channel_id,
                'article_id' => $article->id,
            ],
            [
                'approval_status' => $status,
                'validated_at' => now(),
                'decided_at' => $status === ApprovalStatusEnum::PENDING ? null : now(),
            ]
        );
    }

    /**
     * @param  Collection<int, Keyword>  $keywords
     */
    private function evaluateKeywords(Collection $keywords, string $content): ApprovalStatusEnum
    {
        if ($keywords->isEmpty()) {
            return ApprovalStatusEnum::PENDING;
        }

        foreach ($keywords as $keyword) {
            if (stripos($content, $keyword->keyword) !== false) {
                return ApprovalStatusEnum::PENDING;
            }
        }

        return ApprovalStatusEnum::REJECTED;
    }

    private function shouldAutoApprove(Route $route): bool
    {
        if ($route->auto_approve !== null) {
            return $route->auto_approve;
        }

        return ! Setting::isPublishingApprovalsEnabled();
    }
}
