<?php

namespace App\Http\Resources;

use App\Enums\GenderEnum;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Storage;

class ClientFavoriteProviderResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        $provider = $this->resource->relationLoaded('provider') ? $this->resource->provider : null;

        $profileMediaPath = $provider?->relationLoaded('profileMedia') ? $provider->profileMedia?->path : null;

        $dailyPrice8h = $this->daily_price_8h ?? $provider?->daily_price_8h;
        $dailyPrice6h = $this->daily_price_6h ?? $provider?->daily_price_6h;
        $dailyPrice4h = $this->daily_price_4h ?? $provider?->daily_price_4h;
        $dailyPrice2h = $this->daily_price_2h ?? $provider?->daily_price_2h;

        $gender = $this->gender ?? $provider?->gender?->value;

        return [
            'id'             => $this->id,
            'client_id'      => $this->client_id,
            'provider_id'    => $this->provider_id,
            'provider_name'  => $this->provider_name ?? ($provider?->relationLoaded('user') ? $provider->user?->name : null),
            'gender'         => $gender,
            'gender_label'   => GenderEnum::labelFor($gender),
            'city_name'      => $this->city_name      ?? null,
            'average_rating' => $this->average_rating ?? $provider?->average_rating,

            'profile_media_url' => $profileMediaPath
                ? Storage::temporaryUrl($profileMediaPath, now()->addMinutes(60))
                : null,

            'daily_price_8h_base' => $dailyPrice8h,
            'daily_price_6h_base' => $dailyPrice6h,
            'daily_price_4h_base' => $dailyPrice4h,
            'daily_price_2h_base' => $dailyPrice2h,
            'daily_price_8h'      => $this->applyCreditCardFee($dailyPrice8h),
            'daily_price_6h'      => $this->applyCreditCardFee($dailyPrice6h),
            'daily_price_4h'      => $this->applyCreditCardFee($dailyPrice4h),
            'daily_price_2h'      => $this->applyCreditCardFee($dailyPrice2h),
            'total_services '     => $this->total_services ?? $provider?->total_services,
            'notes'               => $this->notes,
            'created_at'          => $this->created_at?->format('Y-m-d H:i'),
            'updated_at'          => $this->updated_at?->format('Y-m-d H:i'),
        ];
    }

    private function applyCreditCardFee(mixed $price): ?float
    {
        if ($price === null) {
            return null;
        }

        $rate = config('services.pagarme.platform_credit_card_fee_rate', 0.16);

        if (is_string($rate)) {
            $rate = str_replace(',', '.', trim($rate));
        }

        $rate = (float) $rate;
        $rate = $rate > 1 ? $rate / 100 : $rate;

        return round((float) $price * (1 + $rate), 2);
    }
}
