<?php

namespace App\Services;

use App\Models\Network;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

class AirtimePricingService
{
    public function __construct(
        protected CommerceSettingService $commerceSettingService
    ) {
    }

    public function settings(): array
    {
        return $this->commerceSettingService->airtimeSettings();
    }

    public function discountPercentForNetwork(Network|string|null $network): float
    {
        $slug = $network instanceof Network
            ? (string) $network->slug
            : (string) ($network ?? '');

        $normalized = Str::lower(trim($slug));
        if (in_array($normalized, ['etisalat', '9_mobile', '9-mobile'], true)) {
            $normalized = '9mobile';
        }

        $settings = $this->settings();

        return round((float) data_get($settings, "discounts.{$normalized}", 0), 2);
    }

    public function assertWithinLimits(float $amount): void
    {
        $amount = round($amount, 2);
        $settings = $this->settings();
        $min = round((float) ($settings['min_amount'] ?? 50), 2);
        $max = round((float) ($settings['max_amount'] ?? 500000), 2);

        if ($amount < $min) {
            throw ValidationException::withMessages([
                'amount' => "Minimum airtime amount is NGN ".number_format($min, 2).'.',
            ]);
        }

        if ($amount > $max) {
            throw ValidationException::withMessages([
                'amount' => "Maximum airtime amount is NGN ".number_format($max, 2).'.',
            ]);
        }
    }

    /**
     * @return array{face_amount:float,discount_percent:float,discount_amount:float,payable_amount:float}
     */
    public function calculatePayable(float $faceAmount, Network|string|null $network): array
    {
        $faceAmount = round($faceAmount, 2);
        $discountPercent = $this->discountPercentForNetwork($network);
        $discountAmount = round(($faceAmount * $discountPercent) / 100, 2);
        $payableAmount = round(max($faceAmount - $discountAmount, 0.01), 2);

        return [
            'face_amount' => $faceAmount,
            'discount_percent' => $discountPercent,
            'discount_amount' => $discountAmount,
            'payable_amount' => $payableAmount,
        ];
    }
}

