<?php

namespace App\Services;

use Illuminate\Http\Request;

class ProductSalePriceService
{
    public const GREATER_THAN_REGULAR_MESSAGE = 'Sale Price cannot be greater than Regular Price.';

    public static function normalizeRequest(Request $request): void
    {
        if (! $request->exists('sale_price')) {
            return;
        }

        $salePrice = $request->input('sale_price');
        $regularPrice = $request->input('price');

        if ($salePrice === null || $salePrice === '') {
            $request->merge(['discount' => 0, 'discount_type' => 'amount']);
            return;
        }

        if (! is_numeric($salePrice) || ! is_numeric($regularPrice)) {
            return;
        }

        $salePrice = (float) $salePrice;
        $regularPrice = (float) $regularPrice;
        if ($salePrice > 0 && $regularPrice > 0 && $salePrice <= $regularPrice) {
            $request->merge([
                'discount' => round($regularPrice - $salePrice, 8),
                'discount_type' => 'amount',
            ]);
        }
    }

    public static function discountPercentage(float $regularPrice, ?float $salePrice): int
    {
        if ($regularPrice <= 0 || $salePrice === null || $salePrice <= 0 || $salePrice >= $regularPrice) {
            return 0;
        }

        return (int) round((($regularPrice - $salePrice) / $regularPrice) * 100);
    }

    public static function apiPricing(float $regularPrice, float $discountAmount): array
    {
        $discountAmount = max($discountAmount, 0);
        $salePrice = $regularPrice > 0 && $discountAmount > 0
            ? round($regularPrice - $discountAmount, 8)
            : null;

        if ($salePrice === null || $salePrice <= 0 || $salePrice >= $regularPrice) {
            $salePrice = null;
            $discountAmount = 0;
        }

        return [
            'regular_price' => $regularPrice,
            'sale_price' => $salePrice,
            'discount_amount' => round($discountAmount, 8),
            'discount_percentage' => self::discountPercentage($regularPrice, $salePrice),
            'legacy_discount_percentage' => $salePrice !== null
                ? round(($discountAmount / $regularPrice) * 100, 2)
                : 0,
        ];
    }
}
