<?php

namespace Modules\CRMCore\App\Http\Controllers\Api;

use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Controller;

class BaseApiController extends Controller
{
    /**
     * Return a success response
     */
    protected function successResponse($data = null, string $message = 'Success', int $code = 200): JsonResponse
    {
        // Check if data is a resource collection with pagination
        if ($data instanceof \Illuminate\Http\Resources\Json\AnonymousResourceCollection) {
            $response = $data->response()->getData(true);

            // If it's a paginated response, restructure it
            if (isset($response['data']) && isset($response['links']) && isset($response['meta'])) {
                return response()->json([
                    'success' => true,
                    'message' => $message,
                    'data' => $response['data'],
                    'links' => $response['links'],
                    'meta' => $response['meta'],
                ], $code);
            }
        }

        return response()->json([
            'success' => true,
            'message' => $message,
            'data' => $data,
        ], $code);
    }

    /**
     * Return an error response
     */
    protected function errorResponse(string $message = 'Error', $errors = null, int $code = 400): JsonResponse
    {
        return response()->json([
            'success' => false,
            'message' => $message,
            'errors' => $errors,
        ], $code);
    }

    /**
     * Return a validation error response
     */
    protected function validationErrorResponse($validator): JsonResponse
    {
        return response()->json([
            'success' => false,
            'message' => 'Validation failed',
            'errors' => $validator->errors(),
        ], 422);
    }

    /**
     * Return an unauthorized response
     */
    protected function unauthorizedResponse(string $message = 'Unauthorized'): JsonResponse
    {
        return $this->errorResponse($message, null, 401);
    }

    /**
     * Return a forbidden response
     */
    protected function forbiddenResponse(string $message = 'Forbidden'): JsonResponse
    {
        return $this->errorResponse($message, null, 403);
    }

    /**
     * Return a not found response
     */
    protected function notFoundResponse(string $message = 'Not found'): JsonResponse
    {
        return $this->errorResponse($message, null, 404);
    }
}
