<?php

declare(strict_types=1);

namespace Maestro\Core\Http\Controllers\Superadmin;

use Illuminate\Http\JsonResponse;
use Maestro\Core\DataTables\DataTableColumnCatalog;
use Maestro\Core\DataTables\DataTableColumnDefaultsMerger;
use Maestro\Core\Http\Controllers\Controller;
use Maestro\Core\Http\Requests\Superadmin\UpdateDataTableColumnDefaultsRequest;
use Maestro\Core\Models\DataTableColumnDefault;

final class DataTableColumnDefaultsController extends Controller
{
    public function __construct(
        private readonly DataTableColumnCatalog $catalog,
        private readonly DataTableColumnDefaultsMerger $merger,
    ) {}

    public function index(): JsonResponse
    {
        $resources = [];
        foreach ($this->catalog->keysSorted() as $resourceKey) {
            $defs = $this->catalog->definitions($resourceKey);
            $merged = $this->merger->buildApiColumns($resourceKey, $defs);
            $row = DataTableColumnDefault::query()->where('resource_key', $resourceKey)->first();
            $resources[] = [
                'resourceKey' => $resourceKey,
                'tableKey' => $this->catalog->tableStateKeyForResource($resourceKey),
                'visibleKeys' => $row ? ($row->visible_keys ?? []) : null,
                'columns' => $merged,
            ];
        }

        return response()->json(['resources' => $resources]);
    }

    public function update(UpdateDataTableColumnDefaultsRequest $request, string $resourceKey): JsonResponse
    {
        if (! $this->catalog->exists($resourceKey)) {
            abort(404, 'Unknown resource key.');
        }

        /** @var list<string> $visibleKeys */
        $visibleKeys = $request->validated('visibleKeys');

        DataTableColumnDefault::query()->updateOrCreate(
            ['resource_key' => $resourceKey],
            ['visible_keys' => $visibleKeys],
        );

        return response()->json(['ok' => true]);
    }

    public function destroy(string $resourceKey): JsonResponse
    {
        if (! $this->catalog->exists($resourceKey)) {
            abort(404, 'Unknown resource key.');
        }

        DataTableColumnDefault::query()->where('resource_key', $resourceKey)->delete();

        return response()->json(['ok' => true]);
    }
}
