<?php

namespace App\Services\Manage;

use App\Enums\PriceType;
use App\Models\CuttingResultPrice;
use Illuminate\Support\Collection;

class CuttingResultPriceResolver
{
    public function resolve(int $productVariantId, PriceType $priceType): ?CuttingResultPrice
    {
        return CuttingResultPrice::query()
            ->where('product_variant_id', $productVariantId)
            ->where('price_type', $priceType)
            ->whereHas('cutting', fn ($query) => $query->verified())
            ->join('cuttings', 'cutting_result_prices.cutting_id', '=', 'cuttings.id')
            ->orderByDesc('cuttings.created_at')
            ->select('cutting_result_prices.*')
            ->first();
    }

    public function latestPricesForVariant(int $productVariantId): array
    {
        $prices = [];

        foreach (PriceType::cases() as $priceType) {
            $price = $this->resolve($productVariantId, $priceType);

            if ($price !== null) {
                $prices[] = $price;
            }
        }

        return $prices;
    }

    public function latestPricesForVariants(array $variantIds): Collection
    {
        if (empty($variantIds)) {
            return collect();
        }

        return CuttingResultPrice::query()
            ->whereIn('product_variant_id', $variantIds)
            ->whereHas('cutting', fn ($query) => $query->verified())
            ->join('cuttings', 'cutting_result_prices.cutting_id', '=', 'cuttings.id')
            ->orderByDesc('cuttings.created_at')
            ->select('cutting_result_prices.*')
            ->get()
            ->groupBy(fn (CuttingResultPrice $price) => $price->product_variant_id.'-'.$price->price_type->value)
            ->map(fn (Collection $group) => $group->first())
            ->values()
            ->groupBy('product_variant_id');
    }
}
