<?php

namespace Database\Seeders\New;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use JsonMachine\Items;
use JsonMachine\JsonDecoder\ExtJsonDecoder;

class ProductStocksSeeder extends Seeder
{
    public function run()
    {
        DB::transaction(function () {
            $items = Items::fromFile(
                database_path('data/stocks.json'),
                ['decoder' => new ExtJsonDecoder(true)]
            );

            // First we update stock in products table, then in inventory_product table
            foreach ($items as $data) {
                DB::table('products')->where('id', $data['item_id'])->update([
                    'stock' => $data['quantity'],
                ]);

                DB::table('inventory_product')
                    ->insert([
                        'product_id' => $data['item_id'],
                        'inventory_id' => $data['warehouse_id'],
                        'stock' => $data['quantity'],
                    ]);
            }

            DB::statement("
                SELECT setval('inventory_product_id_seq', (SELECT MAX(id) from inventory_product))
            ");
        });
    }
}