<?php

namespace App\Http\Controllers\Api\V1;

use App\Helpers\ApiResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\TenantSetting\BulkUpdateSettingsRequest;
use App\Http\Requests\TenantSetting\GetSettingsRequest;
use App\Http\Requests\TenantSetting\UpdateSettingRequest;
use App\Services\TenantSettingService;

class TenantSettingController extends Controller
{
    public function __construct(
        private TenantSettingService $service
    ) {}

    /**
     * 모든 설정 조회 (그룹별)
     */
    public function index(GetSettingsRequest $request)
    {
        $validated = $request->validated();

        if (! empty($validated['group'])) {
            $data = $this->service->getByGroup($validated['group']);
        } else {
            $data = $this->service->getAll();
        }

        return ApiResponse::handle(__('message.fetched'), $data);
    }

    /**
     * 특정 설정 조회
     */
    public function show(string $group, string $key)
    {
        $value = $this->service->get($group, $key);

        return ApiResponse::handle(__('message.fetched'), [
            'group' => $group,
            'key' => $key,
            'value' => $value,
        ]);
    }

    /**
     * 설정 저장/업데이트
     */
    public function store(UpdateSettingRequest $request)
    {
        $validated = $request->validated();

        $setting = $this->service->set(
            $validated['group'],
            $validated['key'],
            $validated['value'],
            $validated['description'] ?? null
        );

        return ApiResponse::handle(__('message.updated'), $setting);
    }

    /**
     * 여러 설정 일괄 저장
     */
    public function bulkUpdate(BulkUpdateSettingsRequest $request)
    {
        $validated = $request->validated();

        $settings = collect($validated['settings'])->mapWithKeys(function ($item) {
            return [$item['key'] => [
                'value' => $item['value'],
                'description' => $item['description'] ?? null,
            ]];
        })->toArray();

        $results = $this->service->setMany($validated['group'], $settings);

        return ApiResponse::handle(__('message.bulk_upsert'), [
            'updated' => count($results),
        ]);
    }

    /**
     * 설정 삭제
     */
    public function destroy(string $group, string $key)
    {
        $deleted = $this->service->delete($group, $key);

        if (! $deleted) {
            return ApiResponse::handle(__('error.not_found'), null, 404);
        }

        return ApiResponse::handle(__('message.deleted'));
    }

    /**
     * 기본 설정 초기화
     */
    public function initialize()
    {
        $results = $this->service->initializeDefaults();

        return ApiResponse::handle(__('message.created'), [
            'initialized' => count($results),
        ]);
    }
}
