<?php

namespace App\Http\Resources;

use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\App;
use Mtc\MercuryDataModels\Audit;
use Mtc\MercuryDataModels\Setting;

class AuditListResource extends JsonResource
{
    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->resource->through(fn(Audit $audit) => [
            'id' => $audit->id,
            'event' => $audit->event,
            'created_at' => $audit->created_at->format('d/m/Y H:i'),
            'user' => $audit->user?->name,
            'auditable_id' => $audit->auditable_id,
            'auditable_type' => $audit->auditable_type,
            'auditable_name' => $audit->name,
        ]);
        $resource = $this->resource->toArray();
        $resource['users'] = tenant()->users()->select(['name', 'users.id'])->get()
            ->map(fn($user) => [
                'id' => $user->id,
                'name' => $user->name
            ])
            ->prepend([
                'name' => 'All',
                'id' => null
            ]);
        $resource['types'] = Audit::query()->distinct()->select('auditable_type')->pluck('auditable_type')
            ->map(fn ($value) => ['value' => $value])
            ->prepend([
                'value' => 'All'
            ]);
        if ($request->filled('type') && $request->input('type') !== 'All') {
            $class_name = class_exists($request->input('type'))
                ? $request->input('type')
                : Relation::getMorphedModel($request->input('type'));
            $resource['entries'] = App::make($class_name)->newQuery()
                ->whereHas('audits')
                ->get()
                ->map(function ($entry) {
                    if ($entry instanceof  Setting) {
                        return [
                            'id' => $entry->id,
                            'name' => "[$entry->id] $entry->tab > $entry->section > $entry->group > $entry->name",
                        ];
                    }
                    return [
                        'id' => $entry->id,
                        'name' => "[$entry->id] " . ($entry->name ?? $entry->title),
                    ];
                })
                ->prepend([
                    'name' => 'All',
                    'value' => null
                ]);
        } else {
            $resource['entries'] = [
                [
                    'name' => 'Please select type',
                    'id' => null
                ]
            ];
        }
        return $resource;
    }
}
