<?php

namespace Database\Seeders\New;

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

class ProductsTableSeeder extends Seeder
{
    public function run()
    {
        DB::transaction(function () {
            $table = 'products';
            $users = User::whereNotNull('options->old_customer_id')->get();

            DB::table($table)->truncate();

            $items = Items::fromFile(
                database_path('data/items.json'),
                ['decoder' => new ExtJsonDecoder(true)]
            );

            foreach ($items as $data) {
                $name = json_decode($data['name']);
                $description = json_decode($data['description']);

                DB::table($table)->insert([
                    'id' => $data['id'],
                    'sku' => $data['sku'],
                    'name' => $name->tm ?? $name->en ?? '',
                    'slug' => $data['slug'],
                    'description' => $description->tm ?? $description->en ?? '',
                    'brand_id' => $data['brand_id'],
                    'is_visible' => $data['is_blocked'],
                    'created_at' => $data['created_at'],
                    'updated_at' => $data['updated_at'],
                ]);

                // We find user with $data->seller_id matching old_customer_id in options, then we get users channel and attach product to it
                $user = $users->firstWhere(function ($user) use ($data) {
                    return $user->options['old_customer_id'] == $data['seller_id'];
                });

                $channel = $user ? $user->channel() : tmpostChannel();
                DB::table('channel_product')->insert([
                    'product_id' => $data['id'],
                    'channel_id' => $channel->id,
                ]);
            }

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