<?php

namespace Database\Seeders\New;

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

class ProductPropertyValuesSeeder extends Seeder
{
    public function run()
    {
        $propertyWithValues = $this->fillPropertyValues();
        $this->fillProductPropertyValues($propertyWithValues);
    }

    private function fillPropertyValues()
    {
        $propertyWithValues = collect();

        DB::transaction(function () use (&$propertyWithValues) {
            $table = 'attribute_values';

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

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

            foreach ($items as $data) {
                DB::table($table)->insert([
                    'id' => $data['id'],
                    'key' => $data['id'],
                    'attribute_id' => $data['property_id'],
                    'value' => str_replace('"tm"', '"tk"', $data['name']),
                    'created_at' => $data['created_at'],
                    'updated_at' => $data['updated_at'],
                ]);

                $propertyWithValues->push([
                    'attribute_id' => $data['property_id'],
                    'value_id' => $data['id'],
                ]);
            }

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

        return $propertyWithValues;
    }

    private function fillProductPropertyValues($propertyWithValues)
    {
        DB::transaction(function () use ($propertyWithValues) {
            $table = 'attribute_value_product_attribute';

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

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

            foreach ($items as $data) {
                DB::table($table)->insert([
                    'product_attribute_id' => $propertyWithValues->firstWhere('value_id', $data['property_value_id'])['attribute_id'],
                    'attribute_value_id' => $data['property_value_id'],
                ]);
            }

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