<?php

namespace App\Http\Controllers\Api\Settings;

use App\Http\Controllers\Api\Core\BaseApiController;
use App\Http\Requests\Preferences\PreferencesIndexRequest;
use App\Http\Requests\Preferences\PreferencesUpsertRequest;
use App\Http\Resources\Preferences\PreferencesCollection;
use App\Http\Resources\Preferences\PreferencesResource;
use App\Models\Preferences;
use App\Services\Preferences\PreferencesCommandService;
use App\Services\Preferences\PreferencesQueryService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;

class PreferencesController extends BaseApiController
{
    public function __construct(
        private PreferencesQueryService $queryService,
        private PreferencesCommandService $commandService
    ) {
        parent::__construct();
    }

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

        $filters = $request->validated();
        $page = (int) ($filters['page'] ?? 1);
        $perPage = (int) ($filters['per_page'] ?? 20);

        $rows = $this->queryService->paginate($filters, $page, $perPage);
        $collection = new PreferencesCollection($rows);

        return $this->success([
            'preferences' => $collection->toArray($request),
            'meta' => $collection->with($request)['meta'],
        ]);
    }

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

        $payload = $this->queryService->getForUser($guard);

        return $this->success([
            'preferences' => new PreferencesResource($payload['preferences']),
            'options' => $payload['options'],
        ]);
    }

    public function showForUser(int $userId): JsonResponse
    {
        $row = Preferences::query()->where('user_id', $userId)->first();
        if (!$row) {
            return $this->error('Preferences not found.', Response::HTTP_NOT_FOUND);
        }

        $this->authorize('view', $row);

        $payload = $this->queryService->getForUser($userId);

        return $this->success([
            'preferences' => new PreferencesResource($payload['preferences']),
            'options' => $payload['options'],
        ]);
    }

    public function store(PreferencesUpsertRequest $request): JsonResponse
    {
        $guard = $this->authenticatedUserIdOrUnauthorized();
        if ($guard instanceof JsonResponse) {
            return $guard;
        }

        try {
            $saved = $this->commandService->upsert($guard, $request->validated());
        } catch (\Throwable $e) {
            Log::error('Preferences save failed: ' . $e->getMessage());
            return $this->error('Unable to save preferences.', Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        $payload = $this->queryService->getForUser($guard);

        return $this->success([
            'preferences' => new PreferencesResource($payload['preferences']),
        ], 'Preferences saved.', $saved->wasRecentlyCreated ? Response::HTTP_CREATED : Response::HTTP_OK);
    }

    public function updateForUser(PreferencesUpsertRequest $request, int $userId): JsonResponse
    {
        $row = Preferences::query()->where('user_id', $userId)->first();
        if ($row) {
            $this->authorize('update', $row);
        }

        try {
            $saved = $this->commandService->upsert($userId, $request->validated());
        } catch (\Throwable $e) {
            Log::error('Preferences update failed: ' . $e->getMessage());
            return $this->error('Unable to save preferences.', Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        $payload = $this->queryService->getForUser($userId);

        return $this->success([
            'preferences' => new PreferencesResource($payload['preferences']),
        ], 'Preferences saved.', $saved->wasRecentlyCreated ? Response::HTTP_CREATED : Response::HTTP_OK);
    }

    public function destroy(int $userId): JsonResponse
    {
        $row = Preferences::query()->where('user_id', $userId)->first();
        if (!$row) {
            return $this->error('Preferences not found.', Response::HTTP_NOT_FOUND);
        }

        $this->authorize('delete', $row);

        try {
            $deleted = $this->commandService->delete($row);
        } catch (\Throwable $e) {
            Log::error('Preferences delete failed: ' . $e->getMessage());
            return $this->error('Unable to delete preferences.', Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        if (!$deleted) {
            return $this->error('Unable to delete preferences.', Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        return $this->success(null, 'Preferences deleted.');
    }

    /**
     * @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;
    }
}
