<?php

use App\Support\Marketplace\MarketplaceFeeRule;
use Illuminate\Support\Facades\DB;
use Spatie\LaravelSettings\Migrations\SettingsBlueprint;
use Spatie\LaravelSettings\Migrations\SettingsMigration;

return new class extends SettingsMigration
{
    public function up(): void
    {
        $this->migrator->inGroup('marketplace', function (SettingsBlueprint $blueprint): void {
            $oldKeys = [
                'tiktok_shop_admin_fee',
                'tiktok_shop_transaction_fee',
                'tiktok_shop_payment_fee',
                'tiktok_shop_affiliate_commission',
                'tiktok_shop_shipping_subsidy',
                'tiktok_shop_vat_rate',
                'shopee_commission_fee',
                'shopee_transaction_fee',
                'shopee_service_fee',
                'shopee_payment_fee',
                'shopee_affiliate_commission',
                'shopee_shipping_subsidy',
                'shopee_voucher_fee',
            ];

            $existing = DB::table('settings')
                ->where('group', 'marketplace')
                ->pluck('name')
                ->toArray();

            foreach ($oldKeys as $key) {
                if (in_array($key, $existing)) {
                    $blueprint->delete($key);
                }
            }

            $newFields = [
                'tiktok_shop_platform_commission',
                'tiktok_shop_logistics_service_fee',
                'tiktok_shop_dynamic_commission',
                'tiktok_shop_order_processing_fee',
                'tiktok_shop_affiliate',
                'tiktok_shop_pre_order_service_fee',
                'shopee_admin_fee',
                'shopee_program_fee',
                'shopee_shipping_savings',
                'shopee_premium',
                'shopee_service_fee',
                'shopee_order_processing_fee',
                'shopee_ams_commission_fee',
                'shopee_pre_order',
                'shopee_live_extra',
            ];

            $current = DB::table('settings')
                ->where('group', 'marketplace')
                ->pluck('name')
                ->toArray();

            foreach ($newFields as $key) {
                if (! in_array($key, $current)) {
                    $blueprint->add($key, MarketplaceFeeRule::defaultPercent(0.0)->toArray());
                }
            }
        });
    }
};
