<?php

namespace Modules\Approval\Transformers;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Modules\Approval\Contracts\ApprovableDocumentInterface;
use Modules\Core\Exceptions\BusinessException;
use Modules\Core\Transformers\ActionUserResource;

class ApprovalRequestListResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     */
    public function toArray(Request $request): array
    {
        $document = $this->document();

        return [
            'id' => $this->id,
            'workflow' => [
                'id' => $this->workflow->id,
                'name' => $this->workflow->name,
                'code' => $this->workflow->code,
            ],
            'document' => [
                'id' => $document->id,
                'type' => class_basename($document),
                'number' => $document->approvalDocumentNumber(),
                'date' => $document->approvalDocumentDate(),
                'amount' => $document->approvalDocumentAmount(),
                'api_endpoint' => $document->approvalApiEndpoint(),
                'frontend_route' => $document->approvalFrontendRoute(),
            ],
            'current_level' => $this->current_level,
            'status' => $this->status,
            'submitted_at' => $this->submitted_at,
            'submitter' => $this->whenLoaded('submitter', function () {
                return new ActionUserResource($this->submitter);
            }),

        ];
    }

    private function document(): ApprovableDocumentInterface
    {
        $document = $this->approvable;

        if (!$document instanceof ApprovableDocumentInterface) {
            BusinessException::message(
                'Invalid or missing approvable document interface assignment.',
                422
            );
        }

        return $document;
    }
}
