<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class SubscriptionResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'subscription_id'     => $this->subscription_id,
            'reference_id'        => $this->reference_id,

            // ── Policy identifiers ─────────────────────────────────────────
            'cert_id'             => $this->cert_id,
            'policy_number'       => $this->policy_number,
            'policy_status'       => $this->policy_status,
            'policy_status_label' => $this->statusLabel(),

            // ── Plan / Product snapshot ────────────────────────────────────
            'plan' => [
                'plan_id'          => $this->plan_id,
                'plan_name'        => $this->plan?->plan_name,
                'plan_eful_code'   => $this->plan_eful_code,
            ],
            'product' => [
                'product_id'       => $this->product_id,
                'variant'          => $this->variant,
                'variant_label'    => ucfirst($this->variant),
                'efu_product_name' => $this->efu_product_name,
            ],

            // ── Pricing ───────────────────────────────────────────────────
            'pricing' => [
                // Total is what gets charged — sum of all members
                'total_premium_pkr'    => (float) ($this->total_premium ?? $this->premium),
                'total_premium_fmt'    => 'Rs. ' . number_format($this->total_premium ?? $this->premium, 0) . '/- Yearly',
                'total_premium_paisa'  => $this->total_premium_paisa ?? $this->premium_paisa,
                'currency'             => $this->currency,
                'members_count'        => $this->members_count ?? 1,

                // Highest age group among all insured members (oldest person's bracket)
                'applicable_age_group' => $this->resolveHighestAgeGroup(),
            ],

            // ── Payment ───────────────────────────────────────────────────
            'payment' => [
                'transaction_id'      => $this->transaction_id,
                'payment_order_id'    => $this->payment_order_id,
                'payment_order_title' => $this->payment_order_title,
            ],

            // ── Dates ─────────────────────────────────────────────────────
            'dates' => [
                'subscription_timestamp' => $this->subscription_timestamp?->toISOString(),
                'coverage_start_date'    => $this->coverage_start_date?->format('Y-m-d'),
                'coverage_end_date'      => $this->coverage_end_date?->format('Y-m-d'),
                'expiry_date'            => $this->expiry_date?->format('Y-m-d'),
                'grace_period_days'      => $this->grace_period_days,
                'grace_period_end_date'  => $this->grace_period_end_date?->format('Y-m-d'),
                'activated_at'           => $this->activated_at?->toISOString(),
            ],

            // ── Customer ──────────────────────────────────────────────────
            'customer' => [
                'customer_id' => $this->customer_id,
                'full_name'   => $this->customer?->full_name,
                'msisdn'      => $this->customer?->msisdn,
            ],

            // ── Renewal ───────────────────────────────────────────────────
            'is_renewal'                   => $this->is_renewal,
            'renewed_from_subscription_id' => $this->renewed_from_subscription_id,

            // ── Members (self + dependents) ───────────────────────────────
            'members' => SubscriptionMemberResource::collection(
                $this->whenLoaded('members')
            ),

            'created_at' => $this->created_at?->toISOString(),
            'updated_at' => $this->updated_at?->toISOString(),
        ];
    }

    /**
     * Return the contribution_age_group of the member with the
     * highest age_in_months — i.e. the oldest insured person.
     * Falls back to the subscription's own age group if members not loaded.
     */
    private function resolveHighestAgeGroup(): string
    {
        // Members relation must be loaded — if not, fall back to self
        if ($this->relationLoaded('members') && $this->members->isNotEmpty()) {
            $oldest = $this->members->sortByDesc('age_in_months')->first();
            return $oldest->contribution_age_group;
        }

        // Fallback — solo subscriber (no dependents)
        return $this->contribution_age_group ?? '';
    }

    private function statusLabel(): string
    {
        return match ($this->policy_status) {
            'pending_payment' => 'Pending Payment',
            'active'          => 'Active',
            'expired'         => 'Expired',
            'cancelled'       => 'Cancelled',
            'failed'          => 'Payment Failed',
            'grace_period'    => 'Grace Period',
            'suspended'       => 'Suspended',
            default           => ucfirst($this->policy_status),
        };
    }
}