<?php

namespace App\Http\Resources;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

/**
 * Base API resource with consistent envelope format:
 * { success: bool, data: mixed, error: ?string, meta: ?array }
 */
class BaseResource extends JsonResource
{
    protected bool $success = true;
    protected ?string $errorMessage = null;
    protected ?array $metaData = null;
    protected int $statusCode = 200;

    public function withSuccess(bool $success): self
    {
        $this->success = $success;

        return $this;
    }

    public function withError(?string $message): self
    {
        $this->success = false;
        $this->errorMessage = $message;

        return $this;
    }

    public function withMeta(?array $meta): self
    {
        $this->metaData = $meta;

        return $this;
    }

    public function withStatusCode(int $code): self
    {
        $this->statusCode = $code;

        return $this;
    }

    /**
     * @param  mixed  $resource
     */
    public static function makeEnvelope($resource, bool $success = true, ?string $error = null, ?array $meta = null, int $status = 200): JsonResponse
    {
        return response()->json([
            'success' => $success,
            'data' => $resource,
            'error' => $error,
            'meta' => $meta,
        ], $status);
    }

    public function toResponse($request): JsonResponse
    {
        return response()->json([
            'success' => $this->success,
            'data' => $this->resolve($request),
            'error' => $this->errorMessage,
            'meta' => $this->metaData,
        ], $this->statusCode);
    }

    /**
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return parent::toArray($request);
    }
}
