<?php

namespace App;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Mtc\MercuryDataModels\Shortcode;
use Mtc\MercuryDataModels\ShortcodeCondition;
use Mtc\MercuryDataModels\Vehicle;

class ShortcodeHelper
{
    private static Collection $shortcodes;
    public static function replaceShortcodes($content)
    {
        if (!is_string($content)) {
            return $content;
        }

        $shortcodes = self::loadShortcodes();
        $allCodes = $shortcodes->pluck('code')
            ->map(fn ($code) => '{{' . $code . '}}')
            ->toArray();
        if (Str::contains($content, $allCodes) === false) {
            return $content;
        }

        foreach ($shortcodes as $shortcode) {
            if (Str::contains($content, '{{' . $shortcode->code . '}}')) {
                $content = str_replace('{{' . $shortcode->code . '}}', self::getShortcodeValue($shortcode), $content);
            }
        }
        return $content;
    }

    private static function loadShortcodes(): Collection
    {
        if (!isset(self::$shortcodes)) {
            self::$shortcodes = Shortcode::all();
        }
        return self::$shortcodes;
    }

    private static function getShortcodeValue(Shortcode $shortcode): string
    {
        $query = Vehicle::query()->active();
        foreach ($shortcode->conditions as $condition) {
            self::applyCondition($query, $condition);
        }
        return match ($shortcode->model) {
            'count' => $query->count(),
            'min_price' => $query->whereNotNull('price')->min('price'),
            'max_price' => $query->max('price'),
            'min_monthly' => $query->whereNotNull('price')->min('monthly_price'),
            'max_monthly' => $query->max('monthly_price'),
        };
    }

    private static function applyCondition(Builder $query, ShortcodeCondition $condition)
    {
        return match ($condition->operator) {
            '=' => $query->where($condition->column, $condition->value),
            '!=' => $query->where($condition->column, '!=', $condition->value),
            '>' => $query->where($condition->column, '>', $condition->value),
            '>=' => $query->where($condition->column, '>=', $condition->value),
            '<' => $query->where($condition->column, '<', $condition->value),
            '<=' => $query->where($condition->column, '<=', $condition->value),
            'is_null' => $query->whereNull($condition->column),
            default => $query,
        };
    }
}
