<?php

declare(strict_types=1);

namespace Maestro\Core\Http\Controllers\Api;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Maestro\Core\Http\Controllers\Controller;
use Maestro\Core\Http\Requests\UpdateUserTableStateRequest;
use Maestro\Core\Models\UserTableState;
use Maestro\Core\Support\KnownTableStateKeys;

final class UserTableStateController extends Controller
{
    public function show(Request $request, string $tableKey): JsonResponse
    {
        if (! KnownTableStateKeys::isKnown($tableKey)) {
            return response()->json(['message' => 'Unknown table key.'], 404);
        }

        $userId = $request->user()->id;
        $row = UserTableState::query()
            ->where('user_id', $userId)
            ->where('table_key', $tableKey)
            ->first();

        return response()->json([
            'state' => $row?->state,
        ]);
    }

    public function update(UpdateUserTableStateRequest $request, string $tableKey): JsonResponse
    {
        if (! KnownTableStateKeys::isKnown($tableKey)) {
            return response()->json(['message' => 'Unknown table key.'], 404);
        }

        $userId = $request->user()->id;
        $state = $request->validated('state');

        UserTableState::query()->updateOrCreate(
            [
                'user_id' => $userId,
                'table_key' => $tableKey,
            ],
            [
                'state' => $state,
            ],
        );

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

    public function destroy(Request $request, string $tableKey): JsonResponse
    {
        if (! KnownTableStateKeys::isKnown($tableKey)) {
            return response()->json(['message' => 'Unknown table key.'], 404);
        }

        UserTableState::query()
            ->where('user_id', $request->user()->id)
            ->where('table_key', $tableKey)
            ->delete();

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