<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;

class BaseApiController extends Controller
{
    /**
     * Success response
     */
    protected function successResponse($data = null, string $message = null, int $code = 200): JsonResponse
    {
        $response = [
            'success' => true,
        ];

        if ($message) {
            $response['message'] = $message;
        }

        if ($data !== null) {
            $response['data'] = $data;
        }

        return response()->json($response, $code);
    }

    /**
     * Error response
     */
    protected function errorResponse(string $message, string $code = 'ERROR', int $httpCode = 400, array $details = null): JsonResponse
    {
        $response = [
            'success' => false,
            'error' => [
                'code' => $code,
                'message' => $message,
            ]
        ];

        if ($details) {
            $response['error']['details'] = $details;
        }

        return response()->json($response, $httpCode);
    }

    /**
     * Get authenticated user from API token
     */
    protected function getAuthenticatedUser()
    {
        return request()->attributes->get('api_user');
    }

    /**
     * Get API token
     */
    protected function getApiToken()
    {
        return request()->attributes->get('api_token');
    }
}
