<?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', 'approvedByUser']);
        $resource = $this->resource->toArray();

        if (!$this->resource->isPendingApproval() && !$this->resource->isRejected()) {
            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']));
        }

        $resource['approval_status'] = $this->resource->approval_status;
        $resource['approval_reason'] = $this->resource->approval_reason;
        $resource['approval_notes'] = $this->resource->approval_notes;
        $resource['approved_at'] = $this->resource->approved_at?->format('d/m/Y H:i');
        $resource['approved_by_user'] = $this->resource->approvedByUser
            ? [
                'name' => $this->resource->approvedByUser->name,
                'email' => $this->resource->approvedByUser->email,
            ]
            : null;

        return $resource;
    }
}
