<?php

namespace App\Http\Resources;

use App\Master\ContentSyncRepository;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class ContentSyncResource extends JsonResource
{
    public static $wrap = '';

    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $repository = new ContentSyncRepository();
        $resource = $this->resource->toArray();
        if (($this->resource->details['direction'] ?? '') === 'pull') {
            $details = $this->resource->details;
            $details['token'] = $this->resource->token;
            tenancy()->initialize($resource['tenant_id']);
            $resource['data'] = $repository->validateImportData(
                $repository->pullDataFromRemote($details),
                $this->resource->details['scope'],
            );
            tenancy()->end();
        } elseif (!empty($resource['data'])) {
            tenancy()->initialize($resource['tenant_id']);
            $resource['data'] = $repository->validateImportData($resource['data'], $this->resource->details['scope']);
            tenancy()->end();
            $resource['has_errors'] = $resource['data']->filter(fn($row) => !empty($row['errors']))->isNotEmpty();
        }

        return $resource;
    }
}
