<?php

namespace Lucent\Http\Controller;

use App\Http\Controllers\Controller;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Lucent\Account\AccountService;
use Lucent\Query\Query;
use Lucent\Svelte\Svelte;
use function Lucent\Response\ok;

class HomeController extends Controller
{
    public function __construct(
        private readonly Svelte         $svelte,
        private readonly AccountService $accountService,
        private readonly Query          $query,
    )
    {
    }

    public function home(): View
    {

        return $this->svelte->render(
            layout: "channel",
            view: "homeIndex",
            title: "Records",
        );
    }

    public function records(Request $request): Response
    {
        $urlParams = $request->all();
        $users = $this->accountService->all();

        $sort = data_get($urlParams, "sort") ?? "-_sys.updatedAt";
        $filter = data_get($urlParams, "filter") ?? [];
        $arguments = array_merge([
            "schema_in" => $this->accountService->currentReadableSchemas(),
            "status_in" => ["draft", "published"]
        ], $filter);

        $limit = 30;

        $graph = $this->query
            ->filter($arguments)
            ->limit($limit)
            ->childrenDepth(1)
            ->parentsDepth(0)
            ->sort($sort)
            ->run();

        return ok([
            "users" => $users,
            "records" => $graph->getRootRecords()->toArray(),
            "graph" => toArray($graph),
            "modalUrl" => $request->fullUrl(),
        ]);
    }
}
