<?php

namespace App\Models;

use App\Traits\HasCodeGeneration;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ProductInventoryVariant extends Model
{
    use HasCodeGeneration;
    protected $fillable = [
        'user_id',
        'shop_id',
        'product_inventory_id',
        'combination_items',
        'combination_key',
        'price_override',
        'currency_code',
        'sku_code',
        'barcode',
        'status',
        'data',
    ];


    protected $casts = [
        'combination_items' => 'array',
        'data' => 'array',
    ];

    /**
     * The part below is for this model relationships
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function inventory(): BelongsTo
    {
        return $this->belongsTo(ProductInventory::class, 'product_inventory_id');
    }

    public function warehouseInventory(): HasOne
    {
        return $this->hasOne(WarehouseInventory::class, 'product_inventory_variant_id');
    }
    /**
     * The above is for this model relationships
     */



    //helpers

    public function  getInventory()
    {
        return $this->warehouseInventory->qty_on_hand;
    }
    public static function resolveCombination(array $combo): array
    {
        // $combo like ["2"=>"1","3"=>"4"]
        // normalize to ints
        $map = collect($combo)->mapWithKeys(fn($itemId, $attrId) => [(int)$attrId => (int)$itemId]);

        // load attributes and only the chosen items
        $attributes = CategoryAttribute::query()
            ->with(['items' => fn($q) => $q->whereIn('id', $map->values())])
            ->whereIn('id', $map->keys())
            ->get()
            ->keyBy('id');

        // build readable result
        return $map->map(function ($itemId, $attrId) use ($attributes) {
            $attr = $attributes[$attrId] ?? null;
            $item = $attr?->items->first();
            return [
                'attribute_id' => $attrId,
                'attribute'    => $attr?->label ?? "Attribute #{$attrId}",
                'item_id'      => $itemId,
                'item'         => $item?->item_value ?? "Item #{$itemId}",
            ];
        })->values()->all();
    }




    protected static function booted()
    {
        static::creating(function (self $model) {
            // sku_code: unique within the same product_inventory_id
            $model->ensureCode('sku_code', 'sku_code', [
                'scope'  => ['product_inventory_id'],
                'prefix' => 'SKU-',
                'length' => 8,
            ]);

            // barcode: globally unique, EAN-13 by default
            $model->ensureCode('barcode', 'barcode', [
                'barcode_standard' => 'ean13',
            ]);
        });
    }
}
