<?php

namespace App\Http\Controllers\Api\Traits;

use Illuminate\Http\Resources\Json\ResourceCollection;

trait ApiResponse
{
    /**
     * Success response.
     *
     * @param  mixed  $data
     * @param  string|null  $message
     * @param  int  $statusCode
     * @return \Illuminate\Http\JsonResponse
     */
    protected function successResponse($data = [], string|null $message = null, int $statusCode = 200, array $extra = [])
    {
        if ($data instanceof ResourceCollection) {
            $response = $data->additional([
                'success' => true,
                'message' => $message ?? __('messages.success'),
                ...$extra
            ])->response()->setStatusCode($statusCode);

            // Remove 'links' from the 'meta' object if it exists
            $originalData = $response->getData(true);
            if (isset($originalData['links'])) {
                unset($originalData['links']);
                $response->setData($originalData);
            }

            $originalData = $response->getData(true);
            if (isset($originalData['meta']['links'])) {
                unset($originalData['meta']['links']);
                $response->setData($originalData);
            }

            return $response;
        }

        return response()->json([
            'success' => true,
            'data' => $data,
            'message' => $message ?? __('messages.success'),
            ...$extra
        ], $statusCode);
    }

    /**
     * Error response.
     *
     * @param  string|null  $message
     * @param  int  $statusCode
     * @param  mixed  $errors
     * @return \Illuminate\Http\JsonResponse
     */
    protected function errorResponse(string $message = null, int $statusCode = 400, $errors = [])
    {
        return response()->json([
            'success' => false,
            'message' => $message ?? __('messages.error'),
            'errors' => $errors,
        ], $statusCode);
    }
}
