<?php

namespace App\Http\Resources;

use App\Traits\LoadsDataFromSource;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Mtc\ContentManager\Models\Page;
use Mtc\MercuryDataModels\Dealership;
use Mtc\MercuryDataModels\NewCar;
use Mtc\MercuryDataModels\Property;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleOffer;

class EnquiryViewResource extends \Mtc\Crm\Http\Resources\EnquiryViewResource
{
    use LoadsDataFromSource;

    public static $wrap = '';

    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    #[\Override]
    public function toArray($request)
    {
        $this->load([
            'form.questionsInclTrashed',
            'form.actions',
            'type',
            'status',
            'actions',
            'valuation',
            'objects.object',
            'answers',
        ]);

        $this->resource->objects
            ->each(fn ($object) => $object->object_url = $this->getReasonUrl($object->object_type, $object->object_id))
            ->filter(fn ($object) => $object->object)
            ->each(fn ($object) => method_exists($object?->object, 'loadEnquiryRelations')
                ? $object->object->loadEnquiryRelations()
                : $object);
        if (!empty($this->resource->reason_type)) {
            $this->resource->reason_url = $this->getReasonUrl($this->resource->reason_type, $this->resource->reason_id);
        }
        $this->actionData();
        $resource = $this->resource->toArray();
        $resource['details'] = $this->enrichDetails();
        $resource['created_at'] = $this->resource->created_at->format('d/m/Y H:i');
        return $resource;
    }

    private function actionData()
    {
        $this->resource->actions
            ->each(function ($action) {
                $action->name = Str::title(str_replace('-', ' ', $action->action_name));
            });
    }

    private function enrichDetails(): Collection
    {
        return collect($this->resource->details)
            ->map(function ($answer) {
                $question = $this->resource
                    ->form
                    ->questionsInclTrashed->where('id', $answer['id'])
                    ->first();
                $answer['question'] = strip_tags((string) $answer['question']);
                $answer['type'] = $question?->type;
                $answer['value'] = match ($answer['type']) {
                    'dealership_id' => Dealership::query()->find($answer['answer'])?->name,
                    'vehicle_id' => Vehicle::query()->find($answer['answer'])?->title,
                    'offer_id' => VehicleOffer::query()->find($answer['answer'])?->name,
                    'new_car_id' => NewCar::query()->find($answer['answer'])?->name,
                    'page_id' => Page::query()->find($answer['answer'])?->title,
                    'file_upload' => empty($answer['answer'])
                        ? null
                        : collect($answer['answer'])->map(fn ($value) => $this->getEnquiryFileUrl($value)),
                    default => null,
                };

                if ($answer['value'] === null) {
                    $source = $question?->data['meta']['options']['source'] ?? null;
                    if (!empty($source) && is_numeric($answer['answer'])) {
                        $answer['value'] = $this->getChoicesFromDataSource($source)
                            ?->firstWhere('id', $answer['answer'])
                            ?->name ?? __('labels.unknown');
                    }
                }

                return $answer;
            });
    }

    private function getReasonUrl(?string $type, $reason_id): string
    {
        return match ($type) {
            'property' => $this->getEditUrlForProperty($reason_id),
            'valuation' => '/manage-content/valuations/view/' . $reason_id,
            'new-car' => '/manage-content/new-vehicles/edit/' . $reason_id,
            default => '/manage-content/' . Str::plural($type)
                . '/edit/' . $reason_id
        };
    }

    private function getEnquiryFileUrl(?string $value): string
    {
        $base_url = app()->isProduction()
            ? rtrim((string) config('app.url'), '/') . '/api/crm/enquiries/files/' . strip_tags((string) $value)
            : route('enquiries.getFile', strip_tags((string) $value));

        return $base_url . '?' .
            http_build_query([
                'tenant' => tenant()->id
            ]);
    }

    private function getEditUrlForProperty(?int $reason_id): string
    {
        $property = Property::query()
            ->with('category')
            ->where('id', $reason_id)
            ->first();

        return $property
            ? '/properties/' . $property->category?->slug . '/edit/' . $property->id
            : '';
    }
}
