<?php

namespace App\Services;

use App\Models\Producto;
use App\Support\OrdenLavanderiaDetalleLineValidator;

/**
 * Vista previa de totales POS (C6) sin persistir — misma lógica que {@see OrdenLavanderiaService::crearOrdenDesdeCarrito}.
 */
class LaundryPosPreviewTotalsService
{
    public function __construct(
        private readonly LaundryPricingService $laundryPricing
    ) {}

    /**
     * @param  array<int, array<string, mixed>>  $items
     * @return array{lines: list<array<string, mixed>>, total: float}
     */
    public function compute(array $items): array
    {
        $idsProducto = collect($items)->pluck('producto_id')->filter(fn ($id) => $id !== null && $id !== '')->map(fn ($id) => (int) $id)->unique()->values()->all();
        $productos = $idsProducto === [] ? collect() : Producto::whereIn('id', $idsProducto)->get()->keyBy('id');

        $lines = [];
        $subtotal = 0.0;
        foreach ($items as $index => $item) {
            if (OrdenLavanderiaDetalleLineValidator::isInformationalItem($item)) {
                $lines[] = [
                    'index' => $index,
                    'kind' => 'informational',
                    'laundry_sale_product_id' => (int) $item['laundry_sale_product_id'],
                    'garment_type_id' => (int) $item['garment_type_id'],
                    'cantidad' => (float) ($item['cantidad'] ?? 1),
                    'precio_unitario' => 0,
                    'subtotal' => 0,
                ];

                continue;
            }

            if (! empty($item['producto_id'])) {
                $p = $productos->get((int) $item['producto_id']);
                if (! $p) {
                    continue;
                }
                $cant = (float) $item['cantidad'];
                $precio = (float) $p->precio;
                $lineSub = round($cant * $precio, 2);
                $subtotal += $lineSub;
                $lines[] = [
                    'index' => $index,
                    'kind' => 'producto',
                    'producto_id' => $p->id,
                    'nombre' => $p->nombre,
                    'precio_unitario' => $precio,
                    'cantidad' => $cant,
                    'subtotal' => $lineSub,
                ];
            } elseif (! empty($item['laundry_sale_product_id'])) {
                $resolved = $this->laundryPricing->previewSaleCatalogLineMoney($item, $index);
                $subtotal += $resolved['subtotal'];
                $lines[] = array_merge(
                    [
                        'index' => $index,
                        'kind' => 'sale_catalog',
                        'laundry_sale_product_id' => (int) $item['laundry_sale_product_id'],
                        'nombre' => $resolved['product_name'],
                    ],
                    $resolved
                );
            } else {
                $resolved = $this->laundryPricing->previewTibuLineMoney($item, $index);
                $subtotal += $resolved['subtotal'];
                $lines[] = array_merge(
                    ['index' => $index, 'kind' => 'tibu'],
                    $resolved
                );
            }
        }

        return [
            'lines' => $lines,
            'total' => round($subtotal, 2),
        ];
    }
}
