<?php

namespace App\Services;

use Carbon\Carbon;

class ManagedInvestmentSchedule
{
    /**
     * Next payout datetime from a base time (matches legacy investment plan intervals).
     */
    public static function nextPayoutFrom(Carbon $base, string $interval): Carbon
    {
        return match ($interval) {
            'Monthly' => $base->copy()->addDays(27),
            'Weekly' => $base->copy()->addDays(6),
            'Daily' => $base->copy()->addHours(23),
            'Hourly' => $base->copy()->addMinutes(54),
            'Every 30 Minutes' => $base->copy()->addMinutes(24),
            'Every 10 Minutes' => $base->copy()->addMinutes(7),
            default => $base->copy()->addDays(27),
        };
    }

    /**
     * Parse strings like "12 Months", "1 Days", "3 Weeks".
     */
    public static function expiresAtFromDuration(string $investmentDuration, ?Carbon $from = null): Carbon
    {
        $from = $from ?? now();
        $investmentDuration = trim($investmentDuration);
        $parts = preg_split('/\s+/', $investmentDuration, 2);
        if (count($parts) < 2) {
            return $from->copy()->addYear();
        }
        $digit = (int) $parts[0];
        $frame = strtolower($parts[1]);
        $singular = rtrim($frame, 's');

        return match ($singular) {
            'day' => $from->copy()->addDays($digit),
            'week' => $from->copy()->addWeeks($digit),
            'month' => $from->copy()->addMonths($digit),
            'year' => $from->copy()->addYears($digit),
            'hour' => $from->copy()->addHours($digit),
            default => $from->copy()->addYear(),
        };
    }

    public static function payoutIncrement(float $principal, string $topupType, float $topupAmount): float
    {
        if ($topupType === 'Percentage') {
            return round(($principal * $topupAmount) / 100, 2);
        }

        return round((float) $topupAmount, 2);
    }
}
