<?php

namespace App\Http\Resources;

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

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

    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    #[\Override]
    public function toArray(Request $request): array
    {
        $repository = new ContentSyncRepository();
        $this->resource->load('user');
        $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();
        }

        if (Auth::id() !== $resource['user_id']) {
            $resource['token'] = str_repeat('*', strlen((string) $resource['token']));
        }

        return $resource;
    }
}
