<?php

namespace App\Domains\Purchase\Resources;

use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Purchase\Models\PurchaseItem;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

/** @mixin PurchaseItem|CartItem */
class PurchaseItemResource extends JsonResource
{
    /** @return array<string, mixed> */
    public function toArray(Request $request): array
    {
        if ($this->resource instanceof PurchaseItem) {
            $imageUrl = $this->imageAttachment?->getTemporaryUrl(1440);
            $attributes = $this->variant_attributes ?? [];

            return [
                'id' => $this->id,
                'quantity' => (int) $this->cantidad,
                'unit_price' => $this->formatMoney($this->precio_unitario),
                'line_total' => $this->formatMoney($this->total),
                'source_catalog_item_id' => $this->source_catalog_item_id,
                'source_variant_id' => $this->source_variant_id,
                'item_details' => [
                    'nombre' => $this->item_nombre,
                    'descripcion' => $this->descripcion,
                    'slug' => $this->slug,
                    'imagen' => $imageUrl,
                    'attributes' => $attributes,
                ],
            ];
        }

        $selectedItem = $this->selectedItem();
        $catalogItem = $this->catalogItem;
        $variant = $this->variant;
        $quantity = (int) ($this->cantidad ?? 0);
        $unitPrice = $this->resolveUnitPrice($selectedItem);
        $lineTotal = $unitPrice * $quantity;
        $imageUrl = $this->resolveImageUrl($selectedItem, $catalogItem);

        return [
            'id' => $this->id,
            'quantity' => $quantity,
            'unit_price' => $this->formatMoney($unitPrice),
            'line_total' => $this->formatMoney($lineTotal),
            'catalog_item_id' => $this->catalog_item_id,
            'variant_id' => $this->variant_id,
            'product' => $catalogItem === null ? null : [
                'id' => $catalogItem->id,
                'nombre' => $catalogItem->nombre,
                'descripcion' => $catalogItem->descripcion,
                'slug' => $catalogItem->slug,
                'imagen' => $imageUrl,
            ],
            'variant' => $variant === null ? null : [
                'id' => $variant->id,
                'attributes' => $this->resolveAttributes($variant),
            ],
            'item_details' => $selectedItem === null ? null : [
                'nombre' => $selectedItem->getName(),
                'descripcion' => $catalogItem?->descripcion,
                'imagen' => $imageUrl,
                'attributes' => $variant === null ? [] : $this->resolveAttributes($variant),
            ],
        ];
    }

    private function resolveUnitPrice(CatalogItem|Variant|null $selectedItem): float
    {
        return (float) ($selectedItem?->getPrice() ?? 0);
    }

    private function resolveImageUrl(
        CatalogItem|Variant|null $selectedItem,
        ?CatalogItem $catalogItem,
    ): ?string {
        $attachment = $selectedItem?->relationLoaded('attachments')
            ? $selectedItem->attachments->first()
            : null;

        if ($attachment === null && $catalogItem?->relationLoaded('attachments')) {
            $attachment = $catalogItem->attachments->first();
        }

        return $attachment?->getTemporaryUrl(1440);
    }

    /** @return array<int, array{name: string, value: mixed}> */
    private function resolveAttributes(Variant $variant): array
    {
        if (! $variant->relationLoaded('definitions')) {
            return [];
        }

        return $variant->definitions
            ->map(fn ($definition): array => [
                'name' => (string) ($definition->itemAttribute?->attribute?->nombre ?? ''),
                'value' => $definition->value,
            ])
            ->filter(fn (array $attribute): bool => $attribute['name'] !== '' || $attribute['value'] !== null)
            ->values()
            ->all();
    }

    private function formatMoney(float|int|string|null $amount): string
    {
        return number_format((float) ($amount ?? 0), 2, '.', '');
    }
}
