<?php

namespace App\Http\Controllers\Api\Settings;

use App\Domains\AI\Models\TenantAiSetting;
use App\Http\Controllers\Controller;
use App\Http\Requests\AI\UpdateAiSettingsRequest;
use Illuminate\Http\JsonResponse;

class AiSettingsController extends Controller
{
    public function show(): JsonResponse
    {
        $settings = $this->settings();

        return response()->json([
            'data' => $settings->toArray(),
        ]);
    }

    public function update(UpdateAiSettingsRequest $request): JsonResponse
    {
        $settings = $this->settings();
        $settings->update($request->validated());

        return response()->json([
            'data' => $settings->fresh()->toArray(),
        ]);
    }

    protected function settings(): TenantAiSetting
    {
        return TenantAiSetting::query()->firstOrCreate(
            ['tenant_id' => request()->user()->tenant_id],
            [
                'ai_enabled' => true,
                'allowed_features' => config('ai.feature_defaults'),
                'default_language' => 'en',
                'tone_style' => 'professional',
                'human_approval_required' => true,
            ]
        );
    }
}
