<?php

namespace App\Services;

use App\Models\Plan;
use App\Models\User;

class PlanPricingService
{
    /**
     * Resolve the effective selling price for a user tier.
     */
    public function resolveSellingPrice(Plan $plan, ?User $user = null): float
    {
        $tier = $this->normalizeTier($user?->customer_tier ?? null);

        if ($tier) {
            $tierPrice = $this->tierPriceFor($plan, $tier);
            if ($tierPrice !== null) {
                return round($tierPrice, 2);
            }
        }

        return round((float) $plan->selling_price, 2);
    }

    /**
     * @return array{subscriber:?float,reseller:?float,agent:?float}
     */
    public function allTierPrices(Plan $plan): array
    {
        return [
            'subscriber' => $this->tierPriceFor($plan, 'subscriber'),
            'reseller' => $this->tierPriceFor($plan, 'reseller'),
            'agent' => $this->tierPriceFor($plan, 'agent'),
        ];
    }

    protected function tierPriceFor(Plan $plan, string $tier): ?float
    {
        if ($plan->relationLoaded('tierPrices')) {
            $row = $plan->tierPrices->firstWhere('tier', $tier);
            return $row ? round((float) $row->price, 2) : null;
        }

        $row = $plan->tierPrices()->where('tier', $tier)->first(['price']);

        return $row ? round((float) $row->price, 2) : null;
    }

    protected function normalizeTier(?string $tier): ?string
    {
        $tier = strtolower(trim((string) $tier));

        return in_array($tier, ['subscriber', 'reseller', 'agent'], true)
            ? $tier
            : null;
    }
}

