<?php

namespace App\Domains\Sale\Resources\AdminApp;

use App\Domains\Logging\Models\ValueChange;
use App\Domains\Purchase\Models\Purchase;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

/** @mixin ValueChange */
class SaleModificationResource extends JsonResource
{
    /** @return array<string, mixed> */
    public function toArray(Request $request): array
    {
        /** @var Purchase|null $sale */
        $sale = $this->whenLoaded('trackable');
        $user = $this->whenLoaded('user');

        return [
            'id' => $this->id,
            'sale_id' => $this->trackable_id,
            'attribute' => $this->attribute,
            'old_value' => $this->old_value,
            'new_value' => $this->new_value,
            'changed_at' => $this->changed_at->utc()->toIso8601String(),
            'date' => $this->changed_at->format('Y-m-d'),
            'time' => $this->changed_at->format('H:i:s'),
            'actor_type' => $this->actor_type->value,
            'sale' => $sale instanceof Purchase ? [
                'id' => $sale->id,
                'customer_name' => $sale->nombre_apellido,
                'status' => $sale->status,
            ] : null,
            'modified_by' => $user ? [
                'id' => $user->id,
                'name' => $user->nombre_apellido,
                'email' => $user->email,
            ] : null,
        ];
    }
}
