<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

namespace App\Business\DataImport;

use App\Business\DataImport\Enums\DataImportRowStatus;
use App\Business\DataImport\Exports\DataImportFailedRowsExport;
use App\Business\DataImport\Support\DataImportRowSnapshotEncoder;
use App\Models\DberpDataImportBatch;
use App\Models\DberpDataImportBatchRow;
use Illuminate\Database\Eloquent\Builder;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

final class DataImportFailedRowsExportService
{
    public function __construct(
        private readonly DataImportTemplateRegistry $templateRegistry,
    ) {}

    public function hasFailedRows(DberpDataImportBatch $batch): bool
    {
        return $this->failedRowsQuery($batch)->exists();
    }

    public function download(DberpDataImportBatch $batch): BinaryFileResponse
    {
        $matrix = $this->buildExportMatrix($batch);

        if ($matrix['rows'] === []) {
            abort(422, (string) __('dberp.data_import.errors.no_failed_rows_to_export'));
        }

        return Excel::download(
            new DataImportFailedRowsExport($matrix['headings'], $matrix['rows']),
            $this->downloadFilename($batch),
        );
    }

    public function downloadFilename(DberpDataImportBatch $batch): string
    {
        $importTypeKey = DataImportTypeReference::from($batch->import_type)->key;

        return sprintf(
            'dberp_import_failed_rows_%s_%s_%s.xlsx',
            $importTypeKey,
            $batch->batch_no,
            now()->format('Ymd_His'),
        );
    }

    /**
     * @return array{headings: list<string>, rows: list<list<string|null>>}
     */
    public function buildExportMatrix(DberpDataImportBatch $batch): array
    {
        $batch->loadMissing('rows');

        $fieldKeys = $this->templateRegistry->headings($batch->import_type);
        $headings = array_merge(
            [(string) __('dberp.data_import.failed_rows_export.source_row_number')],
            array_map(
                fn (string $fieldKey): string => $this->templateRegistry->headingLabel($fieldKey),
                $fieldKeys,
            ),
            [(string) __('dberp.data_import.failed_rows_export.error_reason')],
        );

        $rows = [];

        foreach ($this->failedRowsQuery($batch)->get() as $row) {
            $rows[] = $this->buildExportRow($row, $fieldKeys);
        }

        return [
            'headings' => $headings,
            'rows' => $rows,
        ];
    }

    /**
     * @param  list<string>  $fieldKeys
     * @return list<string|null>
     */
    private function buildExportRow(DberpDataImportBatchRow $row, array $fieldKeys): array
    {
        $snapshot = is_array($row->raw_snapshot)
            ? DataImportRowSnapshotEncoder::forDisplay($row->raw_snapshot)
            : [];

        $line = [(string) $row->row_number];

        foreach ($fieldKeys as $fieldKey) {
            $value = $snapshot[$fieldKey] ?? null;
            $line[] = $value === null || $value === '' ? null : (string) $value;
        }

        $errors = is_array($row->error_messages) ? $row->error_messages : [];
        $line[] = $errors === [] ? null : implode('；', array_map(strval(...), $errors));

        return $line;
    }

    /**
     * @return Builder<DberpDataImportBatchRow>
     */
    private function failedRowsQuery(DberpDataImportBatch $batch): Builder
    {
        return DberpDataImportBatchRow::query()
            ->where('batch_id', $batch->getKey())
            ->where('status', DataImportRowStatus::Failed)
            ->orderBy('row_number');
    }
}
