<?php

namespace App;

use App\Facades\Settings;
use App\Filter\Sorting\VehicleAttribute as VehicleAttributeSorting;
use App\Filter\Sorting\VehicleAttributeNumeric as VehicleAttributeNumericSorting;
use Mtc\MercuryDataModels\CatalogOffer;
use Mtc\MercuryDataModels\CatalogOfferRule;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleOffer;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Mtc\Filter\Contracts\FilterObject;
use App\Http\Resources\VehicleList;
use Mtc\MercuryDataModels\VehicleAttribute;

class VehicleFilter implements FilterObject
{
    private ?Builder $currentQuery = null;
    private array $selectedCatalogOffers = [];
    private bool $catalogOfferResolved = false;
    private array $selectedSrpFeaturedVehicles = [];
    private bool $srpFeaturedResolved = false;
    private array $selectedVehicleOffers = [];
    private bool $vehicleOfferResolved = false;

    private const VEHICLE_OFFER_FILTERABLE_COLUMNS = [
        'make_id',
        'model_id',
        'fuel_type_id',
        'body_style_id',
        'transmission_id',
        'drivetrain_id',
    ];

    /**
     * Set the current query context for catalog offer rule matching
     */
    public function setCurrentQuery(Builder $query): void
    {
        $this->currentQuery = $query;
    }

    /**
     * Instantiate a query for object
     *
     * @return Builder
     */
    public function createQuery(): Builder
    {
        return Vehicle::query()
            ->active()
            ->withRelationshipsForCardView()
            ->when(Settings::get('automotive-vehicle-brand-on-filter-card'), fn ($query) => $query->with('make'));
    }

    /**
     * Fetch results
     *
     * @param Builder $query
     * @return LengthAwarePaginator
     */
    public function getResults(Builder $query): LengthAwarePaginator
    {
        $this->currentQuery = clone $query;
        $pageLimit = Settings::get('filter-results-per-page', Config::get('filter.result_page_limit'));

        $offerCount = count($this->getCatalogOffers());
        if ($offerCount > 0 && $this->getResultCount($query, false) >= $pageLimit) {
            $pageLimit -= $offerCount;
        }

        $vehicleOfferCount = count($this->getVehicleOffers());
        if ($vehicleOfferCount > 0 && $this->getResultCount($query, false) >= $pageLimit) {
            $pageLimit -= $vehicleOfferCount;
        }

        $featuredVehicles = $this->getSrpFeaturedVehicles();
        $featuredCount = count($featuredVehicles);
        if ($featuredCount > 0) {
            $query->whereNotIn('id', array_map(fn ($v) => $v->id, $featuredVehicles));
            $pageLimit -= $featuredCount;
        }

        return $query->paginate(request('perPage', $pageLimit));
    }

    /**
     * Fetch results
     *
     * @param Builder $query
     * @return int
     */
    public function getResultCount(Builder $query, bool $include_extras = true): int
    {
        $this->currentQuery = clone $query;
        $count = $query->count();

        if ($include_extras) {
            $count += count($this->getCatalogOffers());
            $count += count($this->getVehicleOffers());
        }

        return $count;
    }

    /**
     * Format results to response data
     *
     * @param LengthAwarePaginator $results
     * @return JsonResource
     */
    public function format(LengthAwarePaginator $results): JsonResource
    {
        return new VehicleList(
            $results,
            $this->getCatalogOffers(),
            true,
            $this->getSrpFeaturedVehicles(),
            $this->getVehicleOffers(),
        );
    }

    /**
     * Apply filters to query (e.g. when getting values for filters not main object)
     *
     * @param Builder $query
     */
    public function applyFilter(Builder $query): void
    {
        $query->active();
    }

    /**
     * @return bool
     */
    public function catalogOffersEnabled(): bool
    {
        return Settings::get('filter-inject-offers-into-used-car-filter') === true;
    }

    /**
     * @return bool
     */
    private function hasCatalogOffers(): bool
    {
        if (!$this->catalogOffersEnabled()) {
            return false;
        }

        return count($this->getCatalogOffers()) > 0;
    }

    /**
     * @return CatalogOffer[]
     */
    public function getCatalogOffers(): array
    {
        if (!$this->catalogOffersEnabled()) {
            return [];
        }

        if ($this->catalogOfferResolved) {
            return $this->selectedCatalogOffers;
        }

        $this->catalogOfferResolved = true;

        $maxWeighted = (int) Settings::get('catalog-offer-max-weighted', 0);
        $isPageOne = (int) request('page', 1) === 1;

        if ($isPageOne && $maxWeighted > 0) {
            $weightedOffers = CatalogOffer::query()
                ->active()
                ->forVehicles()
                ->where('weight', '>', 0)
                ->with(['rules', 'mediaUses.media'])
                ->orderBy('weight', 'desc')
                ->get();

            foreach ($weightedOffers as $offer) {
                if (count($this->selectedCatalogOffers) >= $maxWeighted) {
                    break;
                }
                if ($this->catalogOfferMatchesQuery($offer)) {
                    $this->selectedCatalogOffers[] = $offer;
                }
            }

            if (!empty($this->selectedCatalogOffers)) {
                return $this->selectedCatalogOffers;
            }
        }

        // Fall back to random selection (page 2+ or when weighted feature is off)
        $offers = CatalogOffer::query()
            ->active()
            ->forVehicles()
            ->with(['rules', 'mediaUses.media'])
            ->inRandomOrder()
            ->get();

        foreach ($offers->shuffle() as $offer) {
            if ($this->catalogOfferMatchesQuery($offer)) {
                $this->selectedCatalogOffers = [$offer];
                return $this->selectedCatalogOffers;
            }
        }

        return [];
    }

    /**
     * @return VehicleOffer[]
     */
    public function getVehicleOffers(): array
    {
        if ($this->vehicleOfferResolved) {
            return $this->selectedVehicleOffers;
        }

        $this->vehicleOfferResolved = true;

        if (!Settings::get('automotive-srp-vehicle-offers-enabled')) {
            return [];
        }

        if (!$this->stockTypeMatchesCurrentSrp()) {
            return [];
        }

        $maxPerPage = min((int) Settings::get('automotive-srp-vehicle-offers-max-per-page', 0), 5);
        if ($maxPerPage <= 0) {
            return [];
        }

        $isPageOne = (int) request('page', 1) === 1;
        $maxWeighted = (int) Settings::get('vehicle-offer-max-weighted', 0);

        $query = $this->buildVehicleOfferQuery();

        if ($isPageOne && $maxWeighted > 0) {
            $weightedOffers = (clone $query)
                ->where('weight', '>', 0)
                ->orderBy('weight', 'desc')
                ->limit(min($maxWeighted, $maxPerPage))
                ->get();

            if ($weightedOffers->isNotEmpty()) {
                $this->selectedVehicleOffers = $weightedOffers->all();
                return $this->selectedVehicleOffers;
            }
        }

        // Page 1 with no weighted offers, or page 2+: random selection
        $limit = $isPageOne ? $maxPerPage : 1;

        $this->selectedVehicleOffers = $query
            ->inRandomOrder()
            ->limit($limit)
            ->get()
            ->all();

        return $this->selectedVehicleOffers;
    }

    /**
     * Build the base query for vehicle offers, respecting selections that map to vehicle_offers relationships.
     *
     * Selections are slug-based filters from the customer's SRP request (e.g. make=ford).
     * We apply each one to the vehicle offer query as a relationship existence check.
     */
    private function buildVehicleOfferQuery(): Builder
    {
        $query = VehicleOffer::query()
            ->active()
            ->withRelationshipsForCardView();

        $selections = collect(request('selections', []));
        if ($selections->isEmpty()) {
            return $query;
        }

        $selectionToRelationship = [
            'make' => 'make',
            'model' => 'model',
            'fuel-type' => 'fuelType',
            'body-style' => 'bodyStyle',
            'transmission' => 'transmission',
            'drivetrain' => 'drivetrain',
        ];

        foreach ($selectionToRelationship as $selectionType => $relationship) {
            $values = $selections
                ->where('type', $selectionType)
                ->pluck('value')
                ->filter()
                ->values();

            if ($values->isNotEmpty()) {
                $query->whereHas($relationship, fn ($q) => $q->whereIn('slug', $values));
            }
        }

        return $query;
    }

    /**
     * Check if the configured stock type setting matches the current SRP context.
     * - 'used' = setting active when filter has is_new=0
     * - 'new' = setting active when filter has is_new=1
     * - 'both' = always active
     */
    private function stockTypeMatchesCurrentSrp(): bool
    {
        $stockType = Settings::get('automotive-srp-vehicle-offers-stock-type');

        if ($stockType === 'both') {
            return true;
        }

        if ($stockType !== 'used' && $stockType !== 'new') {
            return false;
        }

        $isNewFilter = $this->detectIsNewFilter();

        if ($stockType === 'used') {
            return $isNewFilter === 0 || $isNewFilter === false;
        }

        if ($stockType === 'new') {
            return $isNewFilter === 1 || $isNewFilter === true;
        }

        return false;
    }

    /**
     * Look at the current vehicle query's WHERE clauses to determine if it's filtered to used or new stock.
     */
    private function detectIsNewFilter(): mixed
    {
        if ($this->currentQuery === null) {
            return null;
        }

        foreach ($this->currentQuery->getQuery()->wheres ?? [] as $where) {
            if (($where['column'] ?? null) === 'is_new' && ($where['type'] ?? null) === 'Basic') {
                return $where['value'] ?? null;
            }
        }

        return null;
    }

    /**
     * Check if catalog offer rules match vehicles in the current query
     */
    private function catalogOfferMatchesQuery(CatalogOffer $offer): bool
    {
        if ($offer->rules->isEmpty()) {
            return true;
        }

        if ($this->currentQuery === null) {
            return true;
        }

        $query = clone $this->currentQuery;

        foreach ($offer->rules as $rule) {
            $this->applyRuleToQuery($query, $rule);
        }

        try {
            return $query->exists();
        } catch (\Illuminate\Database\QueryException $e) {
            Log::error('Catalog offer rule query failed', [
                'offer_id' => $offer->id,
                'message' => $e->getMessage(),
            ]);
            return false;
        }
    }

    /**
     * Apply a single rule to the query
     */
    private function applyRuleToQuery(Builder $query, CatalogOfferRule $rule): void
    {
        $value = $this->parseRuleValue($rule->value);

        if ($rule->field === 'label') {
            $this->applyLabelRuleToQuery($query, $rule->condition, $value);
            return;
        }

        $field = $this->resolveFieldName($rule->field);

        match ($rule->condition) {
            '=' => $query->where($field, '=', $value),
            '!=' => $query->where($field, '!=', $value),
            '>' => $query->where($field, '>', $value),
            '>=' => $query->where($field, '>=', $value),
            '<' => $query->where($field, '<', $value),
            '<=' => $query->where($field, '<=', $value),
            'is_null' => $query->whereNull($field),
            'exists' => $query->whereNotNull($field),
            'in' => $query->whereIn($field, (array) $value),
            'not_in' => $query->whereNotIn($field, (array) $value),
            default => null,
        };
    }

    private function applyLabelRuleToQuery(Builder $query, string $condition, mixed $value): void
    {
        $ids = (array) $value;

        match ($condition) {
            '=', 'in' => $query->whereHas('labels', fn ($q) => $q->whereIn('labels.id', $ids)),
            '!=', 'not_in' => $query->whereDoesntHave('labels', fn ($q) => $q->whereIn('labels.id', $ids)),
            default => null,
        };
    }

    /**
     * Resolve virtual field names to actual database columns.
     */
    private function resolveFieldName(string $field): string
    {
        return match ($field) {
            'odometer' => Settings::get('automotive-distance_measurement', 'mi') === 'mi'
                ? 'odometer_mi'
                : 'odometer_km',
            'condition' => 'is_new',
            default => $field,
        };
    }

    /**
     * Parse rule value - decode JSON arrays if present
     */
    private function parseRuleValue(mixed $value): mixed
    {
        if (is_string($value) && str_starts_with($value, '[')) {
            $decoded = json_decode($value, true);
            if (json_last_error() === JSON_ERROR_NONE) {
                return $decoded;
            }
        }

        return $value;
    }

    public function getSrpFeaturedVehicles(): array
    {
        if ($this->srpFeaturedResolved) {
            return $this->selectedSrpFeaturedVehicles;
        }

        $this->srpFeaturedResolved = true;

        if (!Settings::get('automotive-srp-featured-vehicles')) {
            return [];
        }

        $isPageOne = (int) request('page', 1) === 1;
        if (!$isPageOne) {
            return [];
        }

        $max = (int) Settings::get('automotive-srp-featured-max', 0);
        if ($max === 0) {
            return [];
        }

        if ($this->currentQuery === null) {
            return [];
        }

        $this->selectedSrpFeaturedVehicles = (clone $this->currentQuery)
            ->where('srp_featured', true)
            ->where('is_reserved', false)
            ->where('is_sold', false)
            ->limit($max)
            ->get()
            ->all();

        return $this->selectedSrpFeaturedVehicles;
    }

    public function sortOptionName(): string
    {
        return 'vehicles';
    }

    public function additionalSortOptions($activeSortOptionName = '')
    {
        $sortOptions = [];
        $sortableAttributes = VehicleAttribute::query()
            ->where('sortable', 1)
            ->get();

        foreach ($sortableAttributes as $sortableAttribute) {
            if ($sortableAttribute->type === 'boolean') {
                $sortOptions[$sortableAttribute->slug] = VehicleAttributeSorting::class;
            } elseif (in_array($sortableAttribute->type, ['integer', 'number'])) {
                $sortOptions[$sortableAttribute->slug . '-asc'] = VehicleAttributeNumericSorting::class;
                $sortOptions[$sortableAttribute->slug . '-desc'] = VehicleAttributeNumericSorting::class;
            }
        }

        return $sortOptions;
    }
}
