<?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\Customers\Http\Resources\CustomerResource;
use Maestro\Core\Modules\Invoices\Models\Invoice;

/** @mixin Invoice */
class InvoiceResource 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,
            'fiscal_year' => $inv->fiscal_year,
            'customer_id' => $inv->customer_id,
            'credited_invoice_id' => $inv->credited_invoice_id,
            'invoice_date' => $inv->invoice_date?->toDateString(),
            'expiration_date' => $inv->expiration_date?->toDateString(),
            'description' => $inv->description,
            'email_body' => $inv->email_body,
            'subtotal_ex_vat' => (float) $inv->subtotal_ex_vat,
            'total_vat' => (float) $inv->total_vat,
            'total_inc_vat' => (float) $inv->total_inc_vat,
            'finalized_at' => $inv->finalized_at?->toIso8601String(),
            'email_sent_at' => $inv->email_sent_at?->toIso8601String(),
            'is_locked' => $inv->isFinalized(),
            'customer' => $this->when(
                $this->relationLoaded('customer') && $this->customer,
                fn () => new CustomerResource($this->customer)
            ),
            'lines' => InvoiceLineResource::collection($this->whenLoaded('lines')),
        ];
    }
}
