<?php

namespace App\Services\Manage;

use App\Enums\PriceType;
use App\Models\ProductPrice;
use App\Services\Concerns\CachesQuery;
use Illuminate\Support\Collection;

class CuttingResultPriceResolver
{
    use CachesQuery;

    public function resolve(int $productVariantId, PriceType $priceType): ?ProductPrice
    {
        return ProductPrice::query()
            ->where('variant_id', $productVariantId)
            ->where('type', $priceType)
            ->first();
    }

    public function latestPricesForVariant(int $productVariantId): Collection
    {
        return $this->cacheRemember("prices:variant:{$productVariantId}", 900, function () use ($productVariantId) {
            return ProductPrice::query()
                ->where('variant_id', $productVariantId)
                ->get()
                ->map(fn (ProductPrice $price) => (object) [
                    'price_type' => $price->type,
                    'price' => $price->price,
                    'price_formatted' => $price->price_formatted,
                    'cost_per_unit' => 0,
                    'cost_per_unit_formatted' => 'Rp 0',
                ]);
        });
    }

    public function latestPricesForVariants(array $variantIds): Collection
    {
        $cached = $this->cacheRemember('prices:variants:'.md5(implode(',', $variantIds)), 900, function () use ($variantIds) {
            if (empty($variantIds)) {
                return [];
            }

            $productPrices = ProductPrice::query()
                ->whereIn('variant_id', $variantIds)
                ->get()
                ->groupBy(fn (ProductPrice $price) => $price->variant_id.'-'.$price->type->value);

            $results = [];
            foreach ($variantIds as $variantId) {
                foreach (PriceType::cases() as $priceType) {
                    $key = $variantId.'-'.$priceType->value;
                    if ($productPrices->has($key)) {
                        $pp = $productPrices->get($key)->first();
                        $results[$variantId][] = [
                            'price_type' => $pp->type->value,
                            'price' => (int) $pp->price,
                            'price_formatted' => $pp->price_formatted,
                        ];
                    }
                }
            }

            return $results;
        });

        return collect(is_array($cached) ? $cached : [])->map(fn ($prices) => collect($prices));
    }
}
