<?php

namespace App\Http\Resources;

use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Facades\Storage;

class UserResource extends JsonResource
{
  /**
   * Transform the resource into an array.
   *
   * @return array<string, mixed>
   */
  public function toArray(Request $request): array
  {
    return [
      'id'          => $this->id,
      'name'        => $this->name,
      'email'       => $this->email,
      'phone'       => $this->phone,
      'gender'      => $this->provider?->gender?->value,
      'language'    => $this->language,
      'type'        => $this->type,
      'provider_id' => $this->provider?->id,

      'push_notifications_enabled' => $this->push_notifications_enabled,

      'provider_daily_price_8h' => $this->provider?->daily_price_8h,
      'provider_daily_price_6h' => $this->provider?->daily_price_6h,
      'provider_daily_price_4h' => $this->provider?->daily_price_4h,
      'provider_daily_price_2h' => $this->provider?->daily_price_2h,
      'client_id'               => $this->client?->id,
      'profile_photo'           => $this->resolveProfilePhoto(),
      'client_document'         => $this->client?->document,
      'registration_complete'   => $this->registration_complete,

      'provider' => new ProviderResource($this->whenLoaded('provider')),
      'client'   => new ClientResource($this->whenLoaded('client')),

      'created_at' => Carbon::parse($this->created_at)->format('Y-m-d H:i'),
      'updated_at' => Carbon::parse($this->updated_at)->format('Y-m-d H:i'),
    ];
  }

  private function resolveProfilePhoto(): ?string
  {
    if ($this->provider) {
      $path = $this->provider->profileMedia?->path;
    } else {
      $path = $this->client?->profileMedia?->path;
    }

    return $path ? Storage::temporaryUrl($path, now()->addMinutes(60)) : null;
  }

  public static function collection($resource): AnonymousResourceCollection
  {
    return parent::collection($resource);
  }
}
