<?php

namespace App\Traits;

use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Resources\Json\ResourceCollection;
use Symfony\Component\HttpFoundation\Response;

trait ApiResponser
{
    /**
     * نجاح + بيانات (مع أو بدون resource)
     */
    protected function success($data = null, string $message = null, int $code = Response::HTTP_OK)
    {
        $response = [
            'success' => true,
            'message' => $message ?? __('api.success'),
            'data'    => $this->formatData($data),
        ];

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

    /**
     * نجاح مع pagination
     */
    protected function successPaginated($resource, string $message = null, int $code = Response::HTTP_OK)
    {
        $resource = $resource->response()->getData(true);

        return response()->json([
            'success' => true,
            'message' => $message ?? __('api.success'),
            'data'    => $resource['data'],
            'meta'    => $resource['meta'] ?? null,
            'links'   => $resource['links'] ?? null,
        ], $code);
    }

    /**
     * خطأ عام
     */
    protected function error(string $message = null, int $code = Response::HTTP_BAD_REQUEST, $errors = null)
    {
        $response = [
            'success' => false,
            'message' => $message ?? __('api.error'),
        ];

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

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

    /**
     * 404 Not Found
     */
    protected function notFound(string $message = null)
    {
        return $this->error($message ?? __('api.not_found'), Response::HTTP_NOT_FOUND);
    }

    /**
     * 401 Unauthorized
     */
    protected function unauthorized(string $message = null)
    {
        return $this->error($message ?? __('api.unauthorized'), Response::HTTP_UNAUTHORIZED);
    }

    /**
     * 403 Forbidden
     */
    protected function forbidden(string $message = null)
    {
        return $this->error($message ?? __('api.forbidden'), Response::HTTP_FORBIDDEN);
    }

    /**
     * 422 Validation Error
     */
    protected function validationError($errors, string $message = null)
    {
        return $this->error($message ?? __('api.validation_error'), Response::HTTP_UNPROCESSABLE_ENTITY, $errors);
    }

    /**
     * تنسيق البيانات تلقائيًا (Resource أو Collection أو Array)
     */
    private function formatData($data)
    {
        if ($data instanceof JsonResource) {
            return $data->toArray(request());
        }

        if ($data instanceof ResourceCollection) {
            return $data->response()->getData(true)['data'];
        }

        return $data ?? (object)[];
    }

    /**
     * Helper: فقط data بدون success/message (للتوافق مع TranslatableResource)
     */
    protected function dataOnly($data)
    {
        return response()->json([
            'data' => $this->formatData($data)
        ]);
    }
}
