<?php

declare(strict_types=1);

namespace App\Http\Resources;

use App\Models\ConsultationRequest;
use App\Support\FileUrl;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class ServiceRequestResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        /** @var ConsultationRequest $model */
        $model = $this->resource;
        $producer = $model->relationLoaded('producer') ? $model->producer : null;
        $producerUser = $producer?->relationLoaded('user') ? $producer->user : $producer?->user;

        $apiStatus = $this->apiStatus($model);
        $type = $this->apiConsultationType((string) ($model->type ?? ''));
        $priority = $this->apiPriority((string) ($model->priority ?? ''));

        return [
            'id' => $model->id,
            'expert_id' => $model->expert_id,
            'producer_id' => $model->producer_id,
            'consultation_type' => $type,
            'consultation_type_label' => ConsultationRequest::typeOptions()[$model->type] ?? $type,
            'mode' => $model->format,
            'mode_label' => ConsultationRequest::formatOptions()[$model->format] ?? $model->format,
            'priority' => $priority,
            'priority_label' => ConsultationRequest::priorityOptions()[$model->priority] ?? $priority,
            'message' => $model->message,
            'status' => $apiStatus,
            'status_label' => $this->apiStatusLabel($apiStatus),
            'producer_name' => $producer?->brand_name
                ?? ($producerUser ? trim(($producerUser->first_name ?? '') . ' ' . ($producerUser->last_name ?? '')) : null),
            'producer_phone' => $model->producer_contact
                ?? $producer?->work_phone
                ?? $producerUser?->cellphone,
            'producer_address' => $model->production_address
                ?? $producer?->work_address,
            'admin_notes' => $model->admin_notes,
            'provider_can_visit' => $model->provider_can_visit,
            'closed_at' => $model->closed_at?->toISOString(),
            'created_at' => $model->created_at?->toISOString(),
            'updated_at' => $model->updated_at?->toISOString(),
            'expert' => $this->whenLoaded('expert', fn () => [
                'id' => $model->expert?->id,
                'display_name' => $model->expert?->display_name,
                'brand_name' => $model->expert?->brand_name,
                'main_category' => $model->expert?->main_category,
                'work_phone' => $model->expert?->work_phone,
            ]),
            'producer' => $this->when(
                $producer !== null,
                fn () => [
                    'id' => $producer->id,
                    'brand_name' => $producer->brand_name,
                    'work_phone' => $producer->work_phone,
                    'work_address' => $producer->work_address,
                    'unit_images' => FileUrl::urls($producer->unit_images ?? null),
                ]
            ),
        ];
    }

    private function apiStatus(ConsultationRequest $model): string
    {
        return match ($model->status) {
            ConsultationRequest::STATUS_PENDING => 'pending',
            ConsultationRequest::STATUS_REJECTED => 'rejected',
            ConsultationRequest::STATUS_CLOSED => 'closed',
            ConsultationRequest::STATUS_APPROVED => match ($model->provider_can_visit) {
                true => 'accepted',
                false => 'declined',
                default => 'pending_expert',
            },
            default => (string) $model->status,
        };
    }

    private function apiStatusLabel(string $status): string
    {
        return match ($status) {
            'pending' => 'در انتظار بررسی ادمین',
            'pending_expert' => 'در انتظار تایید خدمات‌دهنده',
            'accepted' => 'پذیرفته‌شده',
            'declined' => 'رد شده توسط خدمات‌دهنده',
            'rejected' => 'رد شده توسط ادمین',
            'closed' => 'بسته',
            default => $status,
        };
    }

    private function apiConsultationType(string $type): string
    {
        return match ($type) {
            ConsultationRequest::TYPE_HERD, 'herd' => 'herd_management',
            default => $type !== '' ? $type : 'other',
        };
    }

    private function apiPriority(string $priority): string
    {
        return match ($priority) {
            ConsultationRequest::PRIORITY_NORMAL, 'normal' => 'medium',
            ConsultationRequest::PRIORITY_URGENT, 'urgent' => 'high',
            default => $priority !== '' ? $priority : 'medium',
        };
    }
}
