<?php

namespace App\Http\Controllers\Admin;

use App\Enums\AccrualFrequency;
use App\Http\Controllers\Controller;
use App\Models\InvestmentDuration;
use App\Models\InvestmentSetting;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class InvestmentSettingsController extends Controller
{
    /**
     * Show the investment settings page.
     */
    public function edit(): Response
    {
        return Inertia::render('admin/investment-settings', [
            'settings' => InvestmentSetting::current(),
            'durations' => InvestmentDuration::query()
                ->orderBy('sort_order')
                ->orderBy('months')
                ->get(['id', 'months', 'label', 'is_active']),
        ]);
    }

    /**
     * Update the investment settings.
     */
    public function update(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'min_amount' => ['required', 'numeric', 'min:1'],
            'max_amount' => ['required', 'numeric', 'gt:min_amount'],
            'monthly_return' => ['required', 'numeric', 'min:0'],
            'payment_method' => ['required', 'string', 'max:50'],
            'payment_address' => ['required', 'string', 'max:255'],
            'require_kyc_to_invest' => ['required', 'boolean'],
            'require_kyc_to_withdraw' => ['required', 'boolean'],
            'referral_direct_percent' => ['required', 'numeric', 'min:0', 'max:100'],
            'referral_indirect_percent' => ['required', 'numeric', 'min:0', 'max:100'],
            'referral_direct_earning_limit' => ['nullable', 'numeric', 'min:0'],
            'referral_indirect_earning_limit' => ['nullable', 'numeric', 'min:0'],
            'withdrawal_fee_percent' => ['required', 'numeric', 'min:0', 'max:100'],
            'withdrawal_fee_fixed' => ['required', 'numeric', 'min:0'],
            'min_withdrawal_amount' => ['required', 'numeric', 'min:0'],
            'accrual_day_of_month' => ['required', 'integer', 'min:1', 'max:31'],
            'maintenance_mode_enabled' => ['required', 'boolean'],
            'durations' => ['required', 'array', 'min:1'],
            'durations.*' => ['required', 'integer', 'min:1', 'distinct'],
        ]);

        InvestmentSetting::current()->update([
            'min_amount' => $validated['min_amount'],
            'max_amount' => $validated['max_amount'],
            'monthly_return' => $validated['monthly_return'],
            'payment_method' => $validated['payment_method'],
            'payment_address' => $validated['payment_address'],
            'require_kyc_to_invest' => $validated['require_kyc_to_invest'],
            'require_kyc_to_withdraw' => $validated['require_kyc_to_withdraw'],
            'referral_direct_percent' => $validated['referral_direct_percent'],
            'referral_indirect_percent' => $validated['referral_indirect_percent'],
            'referral_direct_earning_limit' => $validated['referral_direct_earning_limit'] ?? null,
            'referral_indirect_earning_limit' => $validated['referral_indirect_earning_limit'] ?? null,
            'withdrawal_fee_percent' => $validated['withdrawal_fee_percent'],
            'withdrawal_fee_fixed' => $validated['withdrawal_fee_fixed'],
            'min_withdrawal_amount' => $validated['min_withdrawal_amount'],
            'accrual_frequency' => AccrualFrequency::Monthly->value,
            'accrual_day_of_month' => $validated['accrual_day_of_month'],
            'maintenance_mode_enabled' => $validated['maintenance_mode_enabled'],
        ]);

        $durationMonths = collect($validated['durations'])
            ->map(fn (int|string $months): int => (int) $months)
            ->sort()
            ->values();

        InvestmentDuration::query()
            ->whereNotIn('months', $durationMonths)
            ->update(['is_active' => false]);

        $durationMonths->each(function (int $months, int $index): void {
            InvestmentDuration::query()->updateOrCreate(
                ['months' => $months],
                [
                    'label' => "{$months} meses",
                    'sort_order' => $index,
                    'is_active' => true,
                ],
            );
        });

        Inertia::flash('toast', [
            'type' => 'success',
            'message' => 'Parámetros guardados correctamente.',
        ]);

        return to_route('admin.investment-settings.edit');
    }
}
