<?php

namespace App\Http\Resources;

use App\Models\Customer;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

/**
 * @mixin Customer
 */
class CustomerResource extends JsonResource
{
    /**
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'firstName' => $this->first_name,
            'lastName' => $this->last_name,
            'name' => trim($this->first_name.' '.$this->last_name),
            'email' => $this->email,
            'phone' => $this->phone,
            'cnic' => $this->cnic,
            'status' => $this->status->value,
            'address' => $this->address,
            'agentId' => $this->agent_id,
            'agent' => $this->whenLoaded(
                'agent',
                fn (): ?array => $this->agent === null
                    ? null
                    : [
                        'id' => $this->agent->id,
                        'name' => $this->agent->name,
                    ],
            ),
            'createdBy' => $this->whenLoaded(
                'creator',
                fn (): array => [
                    'id' => $this->creator->id,
                    'name' => $this->creator->name,
                    'email' => $this->creator->email,
                ],
                $this->created_by,
            ),
            'documents' => CustomerDocumentResource::collection(
                $this->whenLoaded('documents'),
            ),
            'nominee' => $this->when(
                $this->relationLoaded('nominee'),
                fn (): mixed => $this->nominee === null
                    ? null
                    : NomineeResource::make($this->nominee),
            ),
            'createdAt' => $this->created_at?->toIso8601String(),
            'updatedAt' => $this->updated_at?->toIso8601String(),
        ];
    }
}
