<?php

namespace Common\Database\Datasource;

use Closure;
use Common\Database\Datasource\Filters\AlgoliaFilterer;
use Common\Database\Datasource\Filters\ElasticFilterer;
use Common\Database\Datasource\Filters\MeilisearchFilterer;
use Common\Database\Datasource\Filters\MysqlFilterer;
use Common\Database\Datasource\Filters\TntFilterer;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Pagination\AbstractPaginator;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Laravel\Scout\Builder as ScoutBuilder;
use Laravel\Scout\Searchable;
use const App\Providers\WORKSPACED_RESOURCES;

class Datasource
{
    public EloquentBuilder|Relation $builder;
    protected Model $model;
    protected array $params;
    protected bool $queryBuilt = false;
    public DatasourceFilters $filters;
    public array|null|false $order = null;
    // sometimes we might need to order by ID or something else, if primary column
    // is not guaranteed to be unique, to avoid duplicated items in pagination
    public string|null $secondaryOrderCol = null;
    protected ?ScoutBuilder $scoutBuilder;
    protected ?Closure $queryCallback = null;

    public function __construct(
        $model,
        array $params = [],
        DatasourceFilters|null $filters = null,
        protected string|null $filtererName = 'mysql',
        protected bool $qualifySortColumns = true,
    ) {
        $this->model = $model->getModel();
        $this->params = $this->toCamelCase($params);
        $this->builder = $model instanceof Model ? $model->newQuery() : $model;
        $this->filters =
            $filters ?? new DatasourceFilters($this->params['filters'] ?? null);
    }

    public function paginate(): AbstractPaginator
    {
        $this->buildQuery();
        $perPage = $this->limit();
        $page = (int) $this->param('page', 1);
        $isLengthAware = $this->resolvePaginationMethod() === 'lengthAware';
        $columns = empty($this->builder->getQuery()->columns)
            ? ['*']
            : $this->builder->getQuery()->columns;

        if ($this->scoutBuilder instanceof ScoutBuilder) {
            $this->scoutBuilder->query($this->queryCallback);
            return $isLengthAware
                ? $this->scoutBuilder->paginate($perPage, 'page', $page)
                : $this->scoutBuilder->simplePaginate($perPage, 'page', $page);
        } else {
            if ($this->queryCallback) {
                ($this->queryCallback)($this->builder);
            }
            return $isLengthAware
                ? $this->builder->paginate($perPage, $columns, 'page', $page)
                : $this->builder->simplePaginate(
                    $perPage,
                    $columns,
                    'page',
                    $page,
                );
        }
    }

    public function get(): Collection
    {
        $this->buildQuery();
        return $this->builder->limit($this->limit())->get();
    }

    public function param(string $name, $default = null)
    {
        return Arr::get($this->params, Str::camel($name)) ?: $default;
    }

    public function buildQuery(): self
    {
        if ($this->queryBuilt) {
            return $this;
        }
        $with = array_filter(explode(',', $this->param('with', '')));
        $withCount = array_filter(explode(',', $this->param('withCount', '')));
        $searchTerm = $this->param('query');

        // load specified relations and counts
        if (!empty($with)) {
            $this->builder->with($with);
        }
        if (!empty($withCount)) {
            $this->builder->withCount($withCount);
        }

        $this->applyWorkspaceFilter();

        $filterer = $this->resolveFilterer($searchTerm);
        $this->scoutBuilder = (new $filterer(
            $this->builder,
            $this->filters,
            $searchTerm,
        ))->apply();

        // allow caller class to override order or
        // prevent it completely by setting "false"
        if ($this->order !== false) {
            $order = $this->getOrder();
            if (isset($order['col'])) {
                $orderCol = str_replace(
                    $this->builder->getModel()->getTable() . '.',
                    '',
                    $order['col'],
                );
                $methodName = Str::camel('orderBy' . ucfirst($orderCol));
                $scopeMethodName = 'scope' . ucfirst($methodName);
                if (
                    method_exists($this->builder->getModel(), $methodName) ||
                    method_exists($this->builder->getModel(), $scopeMethodName)
                ) {
                    $this->builder->$methodName($order['dir']);
                } else {
                    $this->builder->orderBy(
                        Str::snake($order['col']),
                        $order['dir'] ?? 'desc',
                    );
                }

                if ($this->secondaryOrderCol) {
                    $this->builder->orderBy(
                        $this->secondaryOrderCol,
                        $order['dir'] ?? 'desc',
                    );
                }
            }
        }

        $this->queryBuilt = true;

        return $this;
    }

    /**
     * Set the callback that will have a chance to modify the final eloquent query that will retrieve results.
     */
    public function setQueryCallback(callable $callback): self
    {
        $this->queryCallback = $callback;
        return $this;
    }

    public function filtererIsMysql(): bool
    {
        return !Arr::get($this->params, 'query') ||
            !in_array(Searchable::class, class_uses_recursive($this->model)) ||
            !$this->filtererName ||
            $this->filtererName === 'mysql';
    }

    private function resolveFilterer(): string
    {
        if ($this->filtererIsMysql()) {
            return MysqlFilterer::class;
        }

        return self::scoutDriverToFilterer($this->filtererName);
    }

    public static function scoutDriverToFilterer(string $driver): string
    {
        return match ($driver) {
            'mysql' => MysqlFilterer::class,
            'meilisearch' => MeilisearchFilterer::class,
            'tntsearch' => TntFilterer::class,
            'algolia' => AlgoliaFilterer::class,
            'elasticsearch' => ElasticFilterer::class,
            default => MysqlFilterer::class,
        };
    }

    private function applyWorkspaceFilter(): void
    {
        if (
            !config('app.workspaces_integrated') ||
            !in_array(get_class($this->model), WORKSPACED_RESOURCES)
        ) {
            return;
        }

        if ($workspaceId = $this->param('workspaceId')) {
            $this->filters->where('workspace_id', '=', $workspaceId);
        } elseif ($userId = $this->param('userId')) {
            $this->filters
                ->where('user_id', '=', $userId)
                ->where('workspace_id', '=', 0);
        }
    }

    public function getOrder(
        string $defaultOrderCol = 'updated_at',
        string $defaultOrderDir = 'desc',
    ): array {
        if (isset($this->order['col'])) {
            $orderCol = $this->order['col'];
            $orderDir = $this->order['dir'];
            // order might be a single string: "column|direction"
        } elseif ($specifiedOrder = $this->param('order')) {
            $parts = preg_split('(\||:)', $specifiedOrder);
            $orderCol = Arr::get($parts, 0, $defaultOrderCol);
            $orderDir = Arr::get($parts, 1, $defaultOrderDir);
            // order might be as separate params
        } elseif ($this->param('orderBy') || $this->param('orderDir')) {
            $orderCol = $this->param('orderBy');
            $orderDir = $this->param('orderDir');
            // try ordering be relevance, if it's a search query and
            // using mysql fulltext, finally default to "updated_at" column
        } elseif ($this->hasRelevanceColumn()) {
            $orderCol = 'relevance';
            $orderDir = 'desc';
        } else {
            $orderCol = $defaultOrderCol;
            $orderDir = $defaultOrderDir;
        }

        if (
            $orderCol !== 'relevance' &&
            !Str::endsWith($orderCol, '_count') &&
            $this->qualifySortColumns
        ) {
            $orderCol = $this->builder->qualifyColumn($orderCol);
        }

        return [
            'col' => $orderCol,
            'dir' => $orderDir,
        ];
    }

    private function toCamelCase(array $params): array
    {
        return collect($params)
            ->keyBy(function ($value, $key) {
                return Str::camel($key);
            })
            ->toArray();
    }

    private function hasRelevanceColumn(): bool
    {
        return !!Arr::first(
            $this->getQueryBuilder()->getColumns() ?? [],
            function ($col) {
                return Str::endsWith($col, 'AS relevance');
            },
        );
    }

    private function limit(): int
    {
        if ($this->param('perPage')) {
            return (int) $this->param('perPage');
        } else {
            return $this->getQueryBuilder()->limit ?? 15;
        }
    }

    private function getQueryBuilder(): QueryBuilder
    {
        $query = $this->builder->getQuery();
        if ($query instanceof EloquentBuilder) {
            $query = $query->getQuery();
        }
        return $query;
    }

    protected function resolvePaginationMethod(): string
    {
        $method = $this->param('paginate', 'simple');

        if ($method === 'preferLengthAware') {
            $tables = explode(',', settings('simple_pagination_tables', ''));
            if (in_array($this->model->getTable(), $tables)) {
                $method = 'simple';
            } else {
                $method = 'lengthAware';
            }
        }

        return $method;
    }
}
