<?php

namespace App\Domains\Tenant\Resources\AdminApp;

use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Models\AttachmentCrop;
use App\Domains\Tenant\Models\WebsiteExtra;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

/**
 * @mixin WebsiteExtra
 */
class WebsiteExtraResource extends JsonResource
{
    /**
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return [
            'codigo' => $this->websiteTypeExtra->codigo,
            'nombre' => $this->websiteTypeExtra->nombre,
            'descripcion' => $this->websiteTypeExtra->descripcion,
            'is_required' => $this->websiteTypeExtra->is_required,
            'is_enabled' => $this->is_enabled,
            'request_rules' => $this->websiteTypeExtra->config_schema['request_rules'] ?? [],
            'config' => $this->formatConfig(
                $this->resolvedConfig(),
                fn (Attachment $attachment): string => $attachment->key
            ),
            'resolved_config' => $this->formatConfig(
                $this->resolvedAdminConfig(),
                fn (Attachment $attachment): string => $attachment->getTemporaryUrl(1440)
            ),
        ];
    }

    private function resolvedAdminConfig(): mixed
    {
        $config = $this->resolvedConfig();

        if (
            $this->websiteTypeExtra->codigo !== 'heroConfig'
            || ! is_array($config)
            || ! ($config['background_image_id'] ?? null) instanceof Attachment
        ) {
            return $config;
        }

        $attachment = $config['background_image_id'];
        $fullRange = ['start_percentage' => 0.0, 'end_percentage' => 100.0];
        $crops = $attachment->cropVariants->keyBy('variant');
        $config['background_image_id'] = [
            'url' => $attachment->getTemporaryUrl(1440),
            'crops' => collect(AttachmentCrop::VARIANTS)->mapWithKeys(
                function (string $variant) use ($crops, $fullRange): array {
                    $crop = $crops->get($variant);

                    return [$variant => [
                        'crop_horizontal' => $crop?->crop_horizontal ?? $fullRange,
                        'crop_vertical' => $crop?->crop_vertical ?? $fullRange,
                    ]];
                }
            )->all(),
        ];

        return $config;
    }

    private function formatConfig(mixed $value, callable $formatAttachment): mixed
    {
        if ($value instanceof Attachment) {
            return $formatAttachment($value);
        }

        if (! is_array($value)) {
            return $value;
        }

        return array_map(
            fn (mixed $item): mixed => $this->formatConfig($item, $formatAttachment),
            $value
        );
    }
}
