<?php

namespace App\Http\Controllers\Api\Settings;

use App\Http\Controllers\Api\Core\BaseApiController;
use App\Http\Requests\Settings\SettingsUpdateRequest;
use App\Http\Resources\Settings\SettingsResource;
use App\Models\Setting;
use App\Services\Settings\SettingsService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;

class SettingsController extends BaseApiController
{
    public function __construct(private SettingsService $settingsService)
    {
        parent::__construct();
    }

    public function index(): JsonResponse
    {
        $this->authorize('viewAny', Setting::class);

        return $this->success([
            'settings' => new SettingsResource($this->settingsService->get()),
        ]);
    }

    public function update(SettingsUpdateRequest $request): JsonResponse
    {
        $settings = Setting::singleton();
        $this->authorize('update', $settings);

        $guard = $this->authenticatedUserIdOrUnauthorized();
        if ($guard instanceof JsonResponse) {
            return $guard;
        }

        try {
            $updated = $this->settingsService->update($request->validated(), $guard);
        } catch (\Throwable $e) {
            Log::error('Settings update failed: ' . $e->getMessage());
            return $this->error('Unable to update settings.', Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        return $this->success([
            'settings' => new SettingsResource($updated),
        ], 'Settings updated.');
    }

    /**
     * @return int|JsonResponse
     */
    private function authenticatedUserIdOrUnauthorized(): int|JsonResponse
    {
        $userId = (int) (auth()->id() ?? 0);
        if ($userId <= 0) {
            return $this->error('Unauthorized.', Response::HTTP_UNAUTHORIZED);
        }

        return $userId;
    }
}
