<?php

namespace Database\Seeders\New;

use App\Models\Ecommerce\Product\Inventory\Inventory;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class SellersTableSeeder extends Seeder
{
    public function run()
    {
        DB::transaction(function () {
            $datas = json_decode(File::get('database/data/sellers.json'));
            $warehouses = json_decode(File::get('database/data/warehouses.json'));
            $table = 'users';

            foreach ($datas as $data) {
                $user = User::create([
                    'first_name' => $data->firstname,
                    'last_name' => $data->lastname,
                    'email' => $data->email,
                    'phone_number' => Str::after($data->phone, '993'),
                    'password' => Hash::make('12345678'),
                    'options' => sprintf('{"old_customer_id":"%s"}', $data->id),
                ]);

                $user->assignRole('vendor');

                $user->channels()->create([
                    'name' => $data->firstname.' '.$data->lastname,
                    'slug' => Str::slug($data->firstname.' '.$data->lastname).'_'.random_int(10000, 9999999),
                ]);

                $this->createWarehouses(warehouses: $warehouses, user: $user, old_user_id: $data->id);
            }

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

    private function createWarehouses(array $warehouses, User $user, int $old_user_id)
    {
        $warehouses = array_filter($warehouses, function ($warehouse) use ($old_user_id) {
            return $warehouse->seller_id == $old_user_id;
        });

        foreach ($warehouses as $warehouse) {
            Inventory::create([
                'id' => $warehouse->id,
                'code' => $warehouse->code,
                'name' => $warehouse->name,
                'region' => 'ag',
                'phone_number' => Str::after($warehouse->phone, '993'),
                'channel_id' => $user->channels()->first()->id,
            ]);
        }
    }
}
