<?php

namespace Database\Seeders\New;

use App\Models\Ecommerce\Product\Order\Payment\OrderPayment;
use App\Models\Ecommerce\Product\Order\Shipping\OrderShipping;
use App\Models\Ecommerce\Product\Order\Status\OrderStatus;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use JsonMachine\Items;
use JsonMachine\JsonDecoder\ExtJsonDecoder;

class OrderSeeder extends Seeder
{
    public function run()
    {
        $this->fillOrders();
        $this->fillOrderItems();
    }

    private function fillOrderItems()
    {
        DB::transaction(function () {
            $table = 'order_items';

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

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

            foreach ($items as $data) {
                $channel_id = DB::table('channel_product')->where('product_id', $data['item_id'])->first()->channel_id ?? tmpostChannel()->id;

                DB::table($table)->insert([
                    'id' => $data['id'],
                    'order_id' => $data['order_id'],
                    'product_id' => $data['item_id'],
                    'quantity' => $data['quantity'],
                    'unit_price_amount' => $data['price'],

                    'channel_id' => $channel_id,

                    'created_at' => $data['created_at'],
                    'updated_at' => $data['updated_at'],
                ]);
            }

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

    private function fillOrders()
    {
        DB::transaction(function () {
            $table = 'orders';

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

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

            foreach ($items as $data) {
                DB::table($table)->insert([
                    'id' => $data['id'],
                    'number' => Str::random(30),
                    'user_id' => $data['customer_id'],
                    'options' => sprintf('{"seller_id":"%s","warehouse_id":"%s"}', $data['seller_id'], $data['warehouse_id']),
                    'status' => $this->formatStatus($data['status']),
                    'shipping_method' => $this->formatShippingMethod($data['delivery_type']),
                    'payment_type_id' => $this->formatPaymentType($data['payment_type']),
                    'notes' => $data['note'],
                    'created_at' => $data['created_at'],
                    'updated_at' => $data['updated_at'],
                    'deleted_at' => $data['deleted_at'],
                ]);
            }

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

    private function formatStatus(string $status): string
    {
        return match ($status) {
            'DRAFT' => OrderStatus::PENDING,
            'COMPLETED' => OrderStatus::COMPLETED,
            'DELIVERED' => OrderStatus::COMPLETED,
            'CANCELLED' => OrderStatus::CANCELLED,
            default => OrderStatus::default(),
        };
    }

    private function formatShippingMethod($shippingMethod): string
    {
        return match ($shippingMethod) {
            'PICK_UP' => OrderShipping::SELF_PICKUP,
            'EXPRESS_DELIVERY' => OrderShipping::EXPRESS,
            'SELECTED_DELIVERY' => OrderShipping::STANDART,
            default => OrderShipping::default(),
        };
    }

    private function formatPaymentType($paymentType): int
    {
        return match ($paymentType) {
            'CASH' => 1,
            'CARD' => 2,
            default => 1,
        };
    }
}