<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Setting;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class SettingsController extends BaseController
{
    /**
     * Display current settings
     */
    public function index(): JsonResponse
    {
        try {
            $settings = [
                'article_processing_enabled' => Setting::isArticleProcessingEnabled(),
                'publishing_approvals_enabled' => Setting::isPublishingApprovalsEnabled(),
                'article_publishing_interval' => Setting::getArticlePublishingInterval(),
                'daily_publish_cap' => Setting::getDailyPublishCap(),
            ];

            return $this->sendResponse($settings, 'Settings retrieved successfully.');
        } catch (\Exception $e) {
            return $this->sendError('Failed to retrieve settings: '.$e->getMessage(), [], 500);
        }
    }

    /**
     * Update settings
     */
    public function update(Request $request): JsonResponse
    {
        try {
            $validated = $request->validate([
                'article_processing_enabled' => 'boolean',
                'publishing_approvals_enabled' => 'boolean',
                'article_publishing_interval' => 'integer|min:0',
                'daily_publish_cap' => 'integer|min:0',
            ]);

            if (isset($validated['article_processing_enabled'])) {
                Setting::setArticleProcessingEnabled($validated['article_processing_enabled']);
            }

            if (isset($validated['publishing_approvals_enabled'])) {
                Setting::setPublishingApprovalsEnabled($validated['publishing_approvals_enabled']);
            }

            if (isset($validated['article_publishing_interval'])) {
                Setting::setArticlePublishingInterval($validated['article_publishing_interval']);
            }

            if (isset($validated['daily_publish_cap'])) {
                Setting::setDailyPublishCap($validated['daily_publish_cap']);
            }

            $updatedSettings = [
                'article_processing_enabled' => Setting::isArticleProcessingEnabled(),
                'publishing_approvals_enabled' => Setting::isPublishingApprovalsEnabled(),
                'article_publishing_interval' => Setting::getArticlePublishingInterval(),
                'daily_publish_cap' => Setting::getDailyPublishCap(),
            ];

            return $this->sendResponse(
                $updatedSettings,
                'Settings updated successfully.'
            );
        } catch (ValidationException $e) {
            return $this->sendValidationError($e->errors());
        } catch (\Exception $e) {
            return $this->sendError('Failed to update settings: '.$e->getMessage(), [], 500);
        }
    }
}
