<?php

namespace Database\Seeders;

use App\Models\Ecommerce\Product\Cart\CartItem;
use Exception;
use File;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class CartItemTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $this->seedOldData();
    }

    /**
     * Seed old postshop data
     */
    public function seedOldData(): void
    {
        CartItem::truncate();

        $datas = collect(json_decode(File::get('database/data/carts.json')));

        $table = 'cart_items';

        foreach ($datas as $data) {
            try {
                DB::table($table)->insert([
                    'id' => $data->id,
                    'user_id' => $data->user_id,
                    'product_id' => $data->product_id,
                    'product_quantity' => $data->product_quantity,
                    'created_at' => $data->created_at,
                    'updated_at' => $data->updated_at,
                ]);
            } catch (Exception $e) {
                info(['cart_items error: ' => $e->getMessage()]);
            }
        }

        DB::statement("
            SELECT setval('{$table}_id_seq', (SELECT MAX(id) from {$table}))
        ");
    }
}
