<?php

declare(strict_types=1);

namespace Maestro\Core\Modules\Invoices\Services;

use Maestro\Core\Models\Organization;
use Maestro\Core\Modules\Invoices\Enums\InvoiceType;
use Maestro\Core\Modules\Invoices\Models\Invoice;

/**
 * @return array<string, mixed>
 */
final class InvoiceDocumentBuilder
{
    public static function build(Invoice $invoice): array
    {
        $org = Organization::instance();
        $type = $invoice->type instanceof InvoiceType ? $invoice->type : InvoiceType::from((string) $invoice->type);
        $lines = $invoice->relationLoaded('lines')
            ? $invoice->lines
            : $invoice->lines()->with(['vatRate'])->orderBy('sort_order')->orderBy('id')->get();

        $rows = [];
        foreach ($lines as $line) {
            $rows[] = [
                'description' => (string) $line->description,
                'quantity' => (float) $line->quantity,
                'unit_price_ex_vat' => (float) $line->unit_price_ex_vat,
                'vat_percent' => (float) ($line->vatRate->rate_percent ?? 0),
                'line_total_ex_vat' => (float) $line->line_total_ex_vat,
                'line_vat_amount' => (float) $line->line_vat_amount,
                'line_total_inc_vat' => (float) $line->line_total_inc_vat,
            ];
        }

        $customer = $invoice->relationLoaded('customer') ? $invoice->customer : $invoice->customer()->first();

        return [
            'is_draft' => $invoice->isDraft(),
            'type' => $type->value,
            'type_label' => $type === InvoiceType::CreditNote ? 'Credit note' : 'Invoice',
            'document_number' => $invoice->document_number,
            'organization' => $org ? [
                'name' => $org->display_name,
                'address' => trim(implode(' ', array_filter([
                    $org->address_line_1 ?? $org->street,
                    $org->postal_code,
                    $org->city,
                ]))),
                'email' => $org->email,
                'phone' => $org->phone,
                'vat_number' => $org->vat_number,
            ] : [],
            'customer' => $customer ? [
                'name' => $customer->name,
                'email' => $customer->email,
            ] : [],
            'invoice_date' => $invoice->invoice_date?->format('Y-m-d'),
            'expiration_date' => $invoice->expiration_date?->format('Y-m-d'),
            'description' => $invoice->description,
            'lines' => $rows,
            'subtotal_ex_vat' => (float) $invoice->subtotal_ex_vat,
            'total_vat' => (float) $invoice->total_vat,
            'total_inc_vat' => (float) $invoice->total_inc_vat,
        ];
    }
}
