<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\OperationLog;
use App\Models\SystemSetting;
use App\Support\ApiResponse;
use hg\apidoc\annotation as Apidoc;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

#[Apidoc\Group('后台')]
#[Apidoc\Title('系统配置')]
#[Apidoc\RouteMiddleware(['jwt.auth'])]
final class SettingController extends Controller
{
    #[Apidoc\Title('配置列表')]
    #[Apidoc\Url('/admin/settings')]
    #[Apidoc\Method('GET')]
    #[Apidoc\RouteMiddleware(['permission:settings'])]
    public function index(): JsonResponse
    {
        return ApiResponse::success(SystemSetting::query()->orderBy('group')->orderBy('key')->get());
    }

    #[Apidoc\Title('保存配置')]
    #[Apidoc\Url('/admin/settings')]
    #[Apidoc\Method('PUT')]
    #[Apidoc\RouteMiddleware(['permission:settings'])]
    public function update(Request $request): JsonResponse
    {
        $data = $request->validate([
            'settings' => ['required', 'array'],
        ]);

        foreach ($data['settings'] as $key => $value) {
            SystemSetting::updateOrCreate(['key' => $key], [
                'value' => $value,
                'group' => str_contains((string) $key, '.') ? explode('.', (string) $key)[0] : 'general',
            ]);
        }

        OperationLog::create([
            'user_id' => $request->user()->id,
            'action' => 'settings.updated',
            'target_type' => 'system',
            'target_id' => null,
            'ip' => $request->ip(),
            'payload' => ['keys' => array_keys($data['settings'])],
        ]);

        return ApiResponse::success(SystemSetting::query()->get(), '配置已保存');
    }
}
