<?php

namespace Inside\BCLH\Actions;

use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Inside\Content\Facades\Schema;
use Inside\LHG\Services\DuplicateLogicService;
use Laminas\Diactoros\Response\JsonResponse;

final class DeclensionContent
{
    protected string $class;

    protected array $relations;

    protected array $files;

    protected string $author;

    public function __construct(protected string $bundle, protected string $uuid)
    {
        $this->class = type_to_class($bundle);
        $this->relations = Schema::getRelations($bundle);
        $this->files = Schema::getFieldListingOfType($bundle, ['file', 'image']);
        $this->author = auth()->user()->uuid;
    }

    public function handle(): array
    {
        Log::info('[BCLH Back] Starting declension action on '.$this->bundle.' identified by '.$this->uuid);
        $source = type_to_class($this->bundle)::query()->with($this->relations)->findOrFail($this->uuid);

        $parent = match ($this->bundle) {
            'sops', 'documents' => $source->uuid,
            'rops' => $source->sops?->first()?->uuid,
            default => null,
        };

        [$origin, $target] = match ($this->bundle) {
            'sops' => ['sops', 'rops'],
            'documents' => ['documents', 'declined_documents'],
            default => [$this->bundle, $this->bundle],
        };

        Log::info('[BCLH Back] The parent '.$target.' of this declesion is '.$parent);

        foreach ($this->relations as $relation) {
            $data = data_get($source, $relation);

            data_set($source, Str::snake($relation), $data instanceof Collection ? $data->pluck('uuid')->toArray() : $data->uuid);
        }

        $data = collect($source->getAttributes())
            ->put('bundle', $target)
            ->put('type', 'node')
            ->when($parent, fn ($current) => $current->put($origin, [$parent]))
            ->put('updated_at', now()->format('Y-m-d H:i:s'))
            ->put('author', $this->author)
            ->put('update_author', auth()->user()->uuid)
            ->put('status', false)
            ->except('uuid', 'uuid_host', 'pid', 'last_update', 'author_id')
            ->put('content', DuplicateLogicService::generateFreshSections($source->section_content));

        Log::info('[BCLH Back] The data for the declension is ready, we are sending a post request to create a new ROPs');
        $response = app()->handle(Request::create('api/v1/content/'.$target, 'POST', $data->toArray()));

        if ($response->status() !== 200) {
            Log::error('[BCLH Back] The declension cannot be saved, something went wrong: '.$response->getContent());

            return [];
        }

        Log::info('[BCLH Back] The declension has been created, we are returning the new content');
        $duplicate = json_decode($response->getContent(), true);

        return [
            'content_type' => $target,
            'uuid' => $duplicate['uuid'],
        ];
    }
}
