<?php

declare(strict_types=1);

namespace App\Support\Print\Documents;

use App\Business\Inventory\Enums\InventoryDocumentStatus;
use App\Models\DberpSalesReturnOrder;
use App\Models\DberpSalesReturnOrderItem;
use App\Services\DberpPermissionService;
use App\Support\DberpNumberFormatter;
use App\Support\Print\Contracts\DberpDocumentPrintPresenter;
use App\Support\Print\DberpPrintViewSupport;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Support\Carbon;

final class SalesReturnPrintPresenter implements DberpDocumentPrintPresenter
{
    public const string DOCUMENT_KEY = 'sales-return';

    public function __construct(
        private readonly DberpPermissionService $permissionService,
    ) {}

    public function documentKey(): string
    {
        return self::DOCUMENT_KEY;
    }

    public function userCanPrint(?Authenticatable $user): bool
    {
        return $this->permissionService->allows($user, DberpPermissionService::VIEW_SALES_RETURN);
    }

    public function prepareViewData(int|string $recordId): array
    {
        $order = DberpSalesReturnOrder::query()
            ->with([
                'customer',
                'warehouse',
                'handlerEmployee',
                'salesOrder',
                'salesOutboundOrder',
                'items' => fn ($query) => $query->orderBy('sort_order')->orderBy('id'),
                'items.product',
            ])
            ->findOrFail($recordId);

        $status = InventoryDocumentStatus::tryFrom((string) $order->status);
        $statusLabel = $status?->label() ?? (string) $order->status;
        $showVoidWatermark = $status === InventoryDocumentStatus::Voided || $order->voided_at !== null;

        return [
            'view' => 'print.documents.sales-return',
            'documentTitle' => (string) __('dberp.print.documents.sales_return'),
            'statusLabel' => $statusLabel,
            'showVoidWatermark' => $showVoidWatermark,
            'printTime' => Carbon::now(),
            'company' => DberpPrintViewSupport::companyProfile(),
            'headerFields' => $this->headerFields($order, $statusLabel),
            'lines' => $order->items->values()->map(
                fn (DberpSalesReturnOrderItem $item, int $index): array => $this->formatLine($item, $index + 1),
            ),
            'totals' => $this->totals($order),
            'signatures' => [
                (string) __('dberp.print.signatures.maker'),
                (string) __('dberp.print.signatures.customer_confirm'),
                (string) __('dberp.print.signatures.warehouse_receive'),
                (string) __('dberp.print.signatures.recheck'),
            ],
        ];
    }

    /**
     * @return list<array{label: string, value: string}>
     */
    private function headerFields(DberpSalesReturnOrder $order, string $statusLabel): array
    {
        $fields = [
            [
                'label' => (string) __('dberp.fields.document_code'),
                'value' => (string) $order->code,
            ],
            [
                'label' => (string) __('dberp.fields.business_time'),
                'value' => $order->business_time?->format('Y-m-d H:i') ?? '—',
            ],
            [
                'label' => (string) __('dberp.print.labels.document_status'),
                'value' => $statusLabel,
            ],
            [
                'label' => (string) __('dberp.print.labels.customer'),
                'value' => (string) ($order->customer?->name ?? '—'),
            ],
            [
                'label' => (string) __('dberp.print.labels.warehouse'),
                'value' => (string) ($order->warehouse?->name ?? '—'),
            ],
        ];

        if ($order->salesOrder !== null) {
            $fields[] = [
                'label' => (string) __('dberp.print.labels.related_order'),
                'value' => (string) $order->salesOrder->code,
            ];
        }

        if ($order->salesOutboundOrder !== null) {
            $fields[] = [
                'label' => (string) __('dberp.fields.sales_outbound_code'),
                'value' => (string) $order->salesOutboundOrder->code,
            ];
        }

        if ($order->handlerEmployee !== null) {
            $fields[] = [
                'label' => (string) __('dberp.fields.handler_employee'),
                'value' => (string) $order->handlerEmployee->name,
            ];
        }

        if (filled($order->reason)) {
            $fields[] = [
                'label' => (string) __('dberp.fields.reason'),
                'value' => (string) $order->reason,
            ];
        }

        if (filled($order->remark)) {
            $fields[] = [
                'label' => (string) __('dberp.fields.remark'),
                'value' => (string) $order->remark,
            ];
        }

        return $fields;
    }

    /**
     * @return array{row_number: int, product_code: string, product_name: string, sku_spec: string, unit_name: string, quantity: string, unit_price: string, line_amount: string, batch_serial: string, remark: string}
     */
    private function formatLine(DberpSalesReturnOrderItem $item, int $rowNumber): array
    {
        $productCode = filled($item->product?->code)
            ? (string) $item->product->code
            : (string) ($item->product_sku_code ?? '—');

        return [
            'row_number' => $rowNumber,
            'product_code' => $productCode,
            'product_name' => (string) ($item->product_sku_name ?? $item->product?->name ?? '—'),
            'sku_spec' => DberpPrintViewSupport::formatSkuSpec($item->product_sku_code, $item->product_sku_spec),
            'unit_name' => (string) ($item->unit_name ?? '—'),
            'quantity' => DberpNumberFormatter::quantity($item->return_quantity),
            'unit_price' => DberpNumberFormatter::money($item->unit_price),
            'line_amount' => DberpNumberFormatter::money($item->return_amount),
            'batch_serial' => DberpPrintViewSupport::formatBatchAndSerial($item->batch_no, $item->serial_numbers),
            'remark' => filled($item->remark) ? (string) $item->remark : '',
        ];
    }

    /**
     * @return list<array{label: string, value: string}>
     */
    private function totals(DberpSalesReturnOrder $order): array
    {
        $totals = [];

        if ($order->total_return_quantity !== null) {
            $totals[] = [
                'label' => (string) __('dberp.print.labels.return_quantity'),
                'value' => DberpNumberFormatter::quantity($order->total_return_quantity),
            ];
        }

        if ($order->total_amount !== null) {
            $totals[] = [
                'label' => (string) __('dberp.fields.total_amount'),
                'value' => DberpNumberFormatter::money($order->total_amount),
            ];
        }

        return $totals;
    }
}
