<?php

namespace Modules\LandedCost\Entities\Drivers;

use Modules\LandedCost\Entities\LcExpense;
use Modules\LandedCost\Entities\LcExpenseDistribution;

abstract class AbstractLandedCostDriver implements LandedCostDriverInterface
{
    /** Build a human-readable product label, appending a meaningful variation name. */
    protected function productLabel($product, $variation): string
    {
        if (!$product) {
            return '-';
        }
        $varName = '';
        if ($product->type == 'variable' && $variation
            && !in_array(strtoupper(trim($variation->name ?? '')), ['DUMMY', ''])) {
            $varName = ' ' . $variation->name;
        }
        return $product->name . $varName;
    }

    /**
     * Sum allocated base amount per purchase_line_id across all of this parent's expenses.
     *
     * @return array [purchase_line_id => total_base_amount]
     */
    protected function allocationsByLine(): array
    {
        $expenseIds = LcExpense::forParent($this->parentType(), $this->parentId())->pluck('id');

        if ($expenseIds->isEmpty()) {
            return [];
        }

        return LcExpenseDistribution::whereIn('lc_expense_id', $expenseIds)
            ->selectRaw('purchase_line_id, SUM(allocated_base_amount) as total_base')
            ->groupBy('purchase_line_id')
            ->pluck('total_base', 'purchase_line_id')
            ->map(fn($v) => (float) $v)
            ->toArray();
    }
}
