<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('investments', function (Blueprint $table): void {
            $table->timestamp('maturity_at')->nullable()->after('confirmed_at');
        });

        Schema::table('investment_settings', function (Blueprint $table): void {
            $table->decimal('withdrawal_fee_percent', 8, 4)->default(0)->after('referral_indirect_percent');
            $table->decimal('withdrawal_fee_fixed', 14, 2)->default(0)->after('withdrawal_fee_percent');
        });

        Schema::table('investment_transactions', function (Blueprint $table): void {
            $table->date('accrual_on')->nullable()->after('applied_percent');
        });

        Schema::table('withdrawal_requests', function (Blueprint $table): void {
            $table->decimal('fee_total', 14, 2)->default(0)->after('amount');
            $table->decimal('net_amount', 14, 2)->nullable()->after('fee_total');
        });

        DB::table('investments')
            ->whereNotNull('confirmed_at')
            ->orderBy('id')
            ->chunkById(100, function (\Illuminate\Support\Collection $rows): void {
                foreach ($rows as $row) {
                    $confirmed = \Carbon\Carbon::parse((string) $row->confirmed_at);
                    $maturityAt = $confirmed->copy()->addMonths((int) $row->duration_months);

                    DB::table('investments')
                        ->where('id', $row->id)
                        ->update(['maturity_at' => $maturityAt]);
                }
            });
    }

    public function down(): void
    {

        Schema::table('withdrawal_requests', function (Blueprint $table): void {
            $table->dropColumn(['fee_total', 'net_amount']);
        });

        Schema::table('investment_transactions', function (Blueprint $table): void {
            $table->dropColumn('accrual_on');
        });

        Schema::table('investment_settings', function (Blueprint $table): void {
            $table->dropColumn(['withdrawal_fee_percent', 'withdrawal_fee_fixed']);
        });

        Schema::table('investments', function (Blueprint $table): void {
            $table->dropColumn('maturity_at');
        });
    }
};
