<?php

namespace Modules\Service\Responses;

use Illuminate\Http\Response;
use Illuminate\Contracts\Support\Responsable;
use Illuminate\Pagination\LengthAwarePaginator;

class ApiSuccessResponse implements Responsable
{
    public function __construct(
        private readonly mixed $data,
        private readonly string $message,
        private readonly mixed $paginatedItem = null,
        private readonly int $code = Response::HTTP_OK,
        private readonly array $metadata = [],
        private readonly array $headers = []
    ) {
    }

    /**
     * @param $request
     * @return \Symfony\Component\HttpFoundation\Response|void
     */
    public function toResponse($request)
    {
        $responeBody = [
            'status'  => $this->code,
            'message' => $this->message,
            'data'    => $this->data,
        ];

        if ($this->metadata) {
            $responeBody['metadata'] = $this->metadata;
        }

        if ($this->paginatedItem instanceof LengthAwarePaginator) {
            $responeBody['metadata'] =
                [
                    'current_page' => $this->paginatedItem->currentPage(),
                    'per_page'     => $this->paginatedItem->perPage(),
                    'last_page'    => $this->paginatedItem->lastPage(),
                    'total'        => $this->paginatedItem->total(),
                    'links'        => [
                        'next' => $this->paginatedItem->nextPageUrl(),
                    ],
                ];
        }

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