<?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('investment_settings', function (Blueprint $table): void {
            $table->string('accrual_frequency', 16)->default('daily')->after('withdrawal_fee_fixed');
            $table->unsignedTinyInteger('accrual_day_of_month')->default(30)->after('accrual_frequency');
        });

        Schema::table('investments', function (Blueprint $table): void {
            $table->date('accrual_through_date')->nullable()->after('maturity_at');
        });

        Schema::table('users', function (Blueprint $table): void {
            $table->boolean('referral_program_enabled')->default(false)->after('referred_by_user_id');
        });

        DB::table('investment_settings')->update([
            'accrual_frequency' => 'daily',
            'accrual_day_of_month' => 30,
        ]);

        DB::table('users')->update(['referral_program_enabled' => true]);

        $gainTypes = ['daily_gain'];

        foreach (DB::table('investments')->pluck('id') as $investmentId) {
            $maxDate = DB::table('investment_transactions')
                ->where('investment_id', $investmentId)
                ->whereIn('type', $gainTypes)
                ->whereNotNull('accrual_on')
                ->max('accrual_on');

            if ($maxDate !== null) {
                DB::table('investments')
                    ->where('id', $investmentId)
                    ->update(['accrual_through_date' => $maxDate]);
            }
        }
        Schema::table('investment_transactions', function (Blueprint $table): void {
            $table->date('gain_period_start')->nullable()->after('accrual_on');
            $table->date('gain_period_end')->nullable()->after('gain_period_start');
        });
    }

    public function down(): void
    {
        Schema::table('investment_transactions', function (Blueprint $table): void {
            $table->dropColumn(['gain_period_start', 'gain_period_end']);
        });

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

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

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