<?php

namespace Database\Seeders\New;

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

class MediaSeeder extends Seeder
{
    public function run()
    {
        DB::transaction(function () {
            $table = 'media';

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

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

            foreach ($items as $data) {
                $modelType = match ($data['model_type']) {
                    'Domain\Brand\Models\Brand' => 'brand',
                    'Domain\Category\Models\Category' => 'category',
                    'Domain\Item\Models\Item' => 'product',
                    'Domain\Promo\Models\Banner' => 'banner',
                    'Domain\Promo\Models\Carousel' => 'channel',
                };

                if ($modelType === 'banner') {
                    continue;
                }

                DB::table($table)->insert([
                    "id" => $data['id'],
                    'model_type' => $modelType,
                    'model_id' => $data['model_id'],
                    'uuid' => $data['uuid'],
                    'collection_name' => 'uploads',
                    'name' => $data['name'],
                    'file_name' => $data['file_name'],
                    'mime_type' => $data['mime_type'],
                    'disk' => $data['disk'],
                    'conversions_disk' => $data['conversions_disk'],
                    'size' => $data['size'],
                    'manipulations' => $data['manipulations'],
                    'custom_properties' => $data['custom_properties'],
                    'generated_conversions' => $data['generated_conversions'],
                    'responsive_images' => $data['responsive_images'],
                    'order_column' => $data['order_column'],
                    'created_at' => $data['created_at'],
                    'updated_at' => $data['updated_at'],
                ]);
            }

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