<?php

namespace Database\Seeders;

use App\Models\Ecommerce\Channel\Channel;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;

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

    /**
     * Started kit
     */
    private function seedStarterKit(): void
    {
        collect([
            [
                'name' => 'Tmpost',
                'slug' => 'tmpost',
                'description' => 'Tmpost default',
                'timezone' => 'Asia/Ashgabat',
                'url' => 'http://shop.post.tm',
                'is_default' => true,
            ],
        ])->each(fn ($data) => Channel::create($data));
    }

    /**
     * Seed old postshop data
     */
    public function seedOldData(): void
    {
        $datas = json_decode(File::get('database/data/channels.json'));
        $relations = collect(json_decode(File::get('database/data/channelables.json')));

        $table = 'channels';
        foreach ($datas as $data) {
            DB::table($table)->insert([
                'id' => $data->id,
                'created_at' => $data->created_at,
                'updated_at' => $data->updated_at,
                'name' => $data->name,
                'slug' => $data->slug,
                'description' => $data->description,
                'timezone' => $data->timezone,
                'url' => $data->url,
                'is_default' => true,
                'is_visible' => $data->is_default,
                'channelables_id' => $relations->firstWhere('channel_id', $data->id)?->channelable_id,
                'channelables_type' => $relations->firstWhere('channel_id', $data->id)?->channelable_type,
            ]);
        }

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