<?php

declare(strict_types=1);

namespace Maestro\Core\Modules\Invoices\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Maestro\Core\Modules\Invoices\Models\Invoice;

/** @mixin Invoice */
class InvoiceListResource extends JsonResource
{
    /**
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        /** @var Invoice $inv */
        $inv = $this->resource;

        return [
            'id' => $inv->id,
            'type' => $inv->type->value,
            'status' => $inv->status->value,
            'issued_via' => $inv->issued_via?->value,
            'document_number' => $inv->document_number,
            'invoice_date' => $inv->invoice_date?->toDateString(),
            'expiration_date' => $inv->expiration_date?->toDateString(),
            'total_inc_vat' => (float) $inv->total_inc_vat,
            'customer' => $this->whenLoaded('customer', fn (): array => [
                'id' => $inv->customer->id,
                'name' => $inv->customer->name,
                'email' => $inv->customer->email,
            ]),
            'customer_name' => $inv->relationLoaded('customer') && $inv->customer
                ? (string) $inv->customer->name
                : null,
        ];
    }
}
