<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\ShopSetting;
use App\Services\ShopCatalogService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ShopSettingController extends Controller
{
    public function __construct(private readonly ShopCatalogService $catalog) {}

    public function index(): JsonResponse
    {
        return response()->json(['data' => $this->catalog->settings(true)]);
    }

    public function update(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'settings' => ['required', 'array'],
            'settings.*' => ['nullable'],
        ]);

        DB::transaction(function () use ($validated): void {
            foreach ($validated['settings'] as $key => $value) {
                $type = match (true) {
                    is_bool($value) => 'boolean',
                    is_int($value) => 'integer',
                    is_float($value) => 'decimal',
                    is_array($value) => 'json',
                    default => 'text',
                };
                ShopSetting::query()->updateOrCreate(
                    ['key' => $key],
                    [
                        'value' => $type === 'json' ? json_encode($value) : (string) $value,
                        'type' => $type,
                        'is_public' => true,
                    ]
                );
            }
        });

        return response()->json([
            'message' => 'Shop settings updated.',
            'data' => $this->catalog->settings(true),
        ]);
    }
}
