<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

/**
 * Used by InventoryMRPController::show()
 *
 * Wraps the array returned by InventoryMRPService::getMRPByItem().
 * Since the service returns a plain array (not an Eloquent model),
 * we extend JsonResource and pass the array directly —
 * Laravel treats it like a collection and exposes keys via $this->resource.
 */
class InventoryMRPDetailResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        $item = $this->resource['item'];

        return [
            'item' => [
                'id'   => $item->id,
                'code' => $item->code,
                'name' => $item->name,

                'category' => $item->relationLoaded('category') && $item->category
                    ? ['id' => $item->category->id, 'name' => $item->category->name]
                    : null,

                'uom' => $item->relationLoaded('uom') && $item->uom
                    ? ['id' => $item->uom->id, 'name' => $item->uom->name]
                    : null,
            ],

            // ── Movement aggregates ───────────────────────────────────────────
            'received'     => (float) ($this->resource['received']     ?? 0),
            'move_order'   => (float) ($this->resource['move_order']   ?? 0),
            'misc_receipt' => (float) ($this->resource['misc_receipt'] ?? 0),
            'misc_issue'   => (float) ($this->resource['misc_issue']   ?? 0),
            'consumption'  => (float) ($this->resource['consumption']  ?? 0),
            'transfer_in'  => (float) ($this->resource['transfer_in']  ?? 0),
            'transfer_out' => (float) ($this->resource['transfer_out'] ?? 0),

            // ── Net stock on hand ─────────────────────────────────────────────
            'soh'          => (float) ($this->resource['soh'] ?? 0),
        ];
    }
}
