<?php

namespace App\Http\Resources;

use Carbon\Carbon;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Str;
use Mtc\Crm\Contracts\EnquiryModel;
use Mtc\Crm\Models\EnquiryObject;
use Mtc\Crm\Models\EnquiryType;
use Mtc\MercuryDataModels\Dealership;

class EnquiryList extends \Mtc\Crm\Http\Resources\EnquiryList
{
    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)
    {
        if ($this->resource instanceof LengthAwarePaginator) {
            $this->resource->getCollection()->load([
                'type',
                'objects' => fn ($query) => $query->where('object_type', 'dealership'),
                'objects.object.franchise',
            ]);
            $this->resource
                ->through(fn (EnquiryModel $enquiry) => $this->mapEntry($enquiry));
        } else {
            $this->resource->load([
                'type',
                'objects' => fn ($query) => $query->where('object_type', 'dealership'),
                'objects.object.franchise',
            ]);
            $this->resource = $this->resource
                ->map(fn (EnquiryModel $enquiry) => $this->mapEntry($enquiry));
        }
        $resource = $this->resource->toArray();
        $resource['filters'] = [
            [
                'name' => 'Partially submitted',
                'value' => 'partiallySubmitted',
            ],
            [
                'name' => 'Archived',
                'value' => 'archived',
            ],
            [
                'name' => 'Has Failed Actions',
                'value' => 'hasFailedActions',
            ],
            [
                'type' => 'list',
                'name' => 'Enquiry Type',
                'values' => EnquiryType::query()
                    ->select('name', 'id')
                    ->whereHas('enquiries')
                    ->get()
                    ->map(fn (EnquiryType $enquiryType) => [
                        'id' => $enquiryType->id,
                        'value' => 'enquiry-type-' . $enquiryType->id,
                        'name' => $enquiryType->name,
                    ]),
            ],
            [
                'type' => 'list',
                'name' => 'Location',
                'values' => Dealership::query()
                    ->select('id', 'name')
                    ->whereIn('id', EnquiryObject::query()
                        ->select('object_id')
                        ->where('object_type', 'dealership'))
                    ->orderBy('name')
                    ->get()
                    ->map(fn (Dealership $dealership) => [
                        'id' => $dealership->id,
                        'value' => 'location-' . $dealership->id,
                        'name' => $dealership->name,
                    ]),
            ],
        ];

        return $resource;
    }

    private function mapEntry(EnquiryModel $enquiry)
    {
        $dealership = $enquiry->objects->firstWhere('object_type', 'dealership')?->object;

        return [
            'id' => $enquiry->id,
            'title' => $enquiry->title,
            'description' => __('labels.submitted_at', [
                'datetime' => Carbon::parse($enquiry->ingested_at)?->format('d/m/Y H:i'),
            ]),
            'metaItems' => [
                $enquiry->form?->name,
                $dealership?->name,
                $dealership?->franchise?->name,
                $enquiry->type?->name,
                $enquiry->actions
                    ->map(function ($action) {
                        if ($action->processed_at) {
                            return Str::title(str_replace('-', ' ', $action->action_name)) . ' - OK';
                        }
                        if ($action->failed_at) {
                            return Str::title(str_replace('-', ' ', $action->action_name)) . ' - Failed';
                        }
                        return Str::title(str_replace('-', ' ', $action->action_name)) . ' - Pending';
                    })->implode('<br/>'),
            ]
        ];
    }
}
