<?php

declare(strict_types=1);

namespace Maestro\Core\Http\Controllers\Superadmin;

use Illuminate\Http\JsonResponse;
use Maestro\Core\DataTables\DataTableColumnDefaultsMerger;
use Maestro\Core\DataTables\DataTableRegistry;
use Maestro\Core\Http\Controllers\Controller;
use Maestro\Core\Http\Requests\Superadmin\UpdateDataTableColumnDefaultsRequest;
use Maestro\Core\Models\DataTableColumnDefault;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

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

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

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

    public function update(UpdateDataTableColumnDefaultsRequest $request, string $resourceKey): JsonResponse
    {
        try {
            $this->registry->resolve($resourceKey);
        } catch (NotFoundHttpException) {
            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
    {
        try {
            $this->registry->resolve($resourceKey);
        } catch (NotFoundHttpException) {
            abort(404, 'Unknown resource key.');
        }

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

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