<?php

declare(strict_types=1);

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

namespace App\Business\DataImport\Handlers;

use App\Business\DataImport\Contracts\DataImportHandler;
use App\Business\DataImport\DataImportExecutionResult;
use App\Business\DataImport\DataImportPrecheckResult;
use App\Business\DataImport\DataImportRowExecutionOutcome;
use App\Business\DataImport\Enums\DataImportRowStatus;
use App\Business\DataImport\Enums\DataImportType;
use App\Business\DataImport\Support\DataImportValueParser;
use App\Models\DberpDataImportBatch;
use App\Models\DberpDataImportBatchRow;
use App\Models\DberpRegion;
use App\Models\DberpSupplier;
use App\Models\DberpSupplierCategory;
use Illuminate\Support\Facades\DB;

final class SupplierImportHandler extends AbstractPartnerMasterImportHandler implements DataImportHandler
{
    public function importType(): DataImportType
    {
        return DataImportType::Supplier;
    }

    protected function partnerModelClass(): string
    {
        return DberpSupplier::class;
    }

    protected function categoryCodeField(): string
    {
        return 'supplier_category_code';
    }

    protected function categoryModelClass(): string
    {
        return DberpSupplierCategory::class;
    }

    protected function categoryForeignKey(): string
    {
        return 'supplier_category_id';
    }

    /**
     * @param  list<DataImportRow>  $rows
     */
    public function precheckRows(array $rows): DataImportPrecheckResult
    {
        $common = $this->precheckCommonPartnerRows($rows);

        $categoryIdsByCode = $this->referenceResolver->supplierCategoryIdsByCodes(
            array_values(array_unique($common['categoryCodesInFile'])),
        );
        $regionsByCode = $this->referenceResolver->regionsByCodes(
            array_values(array_unique($common['regionCodesInFile'])),
        );

        $outcomes = $this->applyCommonPartnerReferenceChecks(
            rows: $rows,
            outcomes: $common['outcomes'],
            codesInFile: $common['codesInFile'],
            regionCodesInFile: $common['regionCodesInFile'],
            categoryCodesInFile: $common['categoryCodesInFile'],
            categoryIdsByCode: $categoryIdsByCode,
            regionsByCode: $regionsByCode,
        );

        return $this->buildPrecheckResult($this->finalizeOutcomes($outcomes));
    }

    public function execute(DberpDataImportBatch $batch): DataImportExecutionResult
    {
        $outcomes = [];
        $importedCount = 0;
        $failedCount = 0;

        $validatedRows = $batch->rows()
            ->where('status', DataImportRowStatus::Validated)
            ->orderBy('row_number')
            ->get();

        $categoryCodes = [];
        $regionCodes = [];

        foreach ($validatedRows as $batchRow) {
            $snapshot = is_array($batchRow->raw_snapshot) ? $batchRow->raw_snapshot : [];
            $categoryCode = DataImportValueParser::trimmed($snapshot['supplier_category_code'] ?? null);
            $regionCode = DataImportValueParser::trimmed($snapshot['region_code'] ?? null);

            if ($categoryCode !== null) {
                $categoryCodes[] = $categoryCode;
            }

            if ($regionCode !== null) {
                $regionCodes[] = $regionCode;
            }
        }

        $categoryIdsByCode = $this->referenceResolver->supplierCategoryIdsByCodes(array_values(array_unique($categoryCodes)));
        $regionsByCode = $this->referenceResolver->regionsByCodes(array_values(array_unique($regionCodes)));

        DB::transaction(function () use ($validatedRows, $categoryIdsByCode, $regionsByCode, &$outcomes, &$importedCount, &$failedCount): void {
            foreach ($validatedRows as $batchRow) {
                $outcome = $this->importRow($batchRow, $categoryIdsByCode, $regionsByCode);
                $outcomes[] = $outcome;

                if ($outcome->imported()) {
                    $importedCount++;
                } else {
                    $failedCount++;
                }
            }
        });

        return new DataImportExecutionResult($outcomes, $importedCount, $failedCount);
    }

    /**
     * @param  array<string, int>  $categoryIdsByCode
     * @param  array<string, DberpRegion>  $regionsByCode
     */
    private function importRow(
        DberpDataImportBatchRow $batchRow,
        array $categoryIdsByCode,
        array $regionsByCode,
    ): DataImportRowExecutionOutcome {
        $snapshot = is_array($batchRow->raw_snapshot) ? $batchRow->raw_snapshot : [];

        try {
            $payload = $this->buildCommonPartnerPayload($snapshot, $categoryIdsByCode, $regionsByCode);
            $supplier = DberpSupplier::query()->create($payload);

            $batchRow->update([
                'status' => DataImportRowStatus::Imported,
                'created_record_type' => DberpSupplier::class,
                'created_record_id' => (int) $supplier->getKey(),
                'error_messages' => null,
            ]);

            return new DataImportRowExecutionOutcome(
                rowNumber: (int) $batchRow->row_number,
                status: DataImportRowStatus::Imported,
                createdRecordType: DberpSupplier::class,
                createdRecordId: (int) $supplier->getKey(),
            );
        } catch (\Throwable $exception) {
            $message = DataImportValueParser::rowError((int) $batchRow->row_number, (string) __('dberp.data_import.validation.import_failed', [
                'reason' => $exception->getMessage(),
            ]));

            $batchRow->update([
                'status' => DataImportRowStatus::Failed,
                'error_messages' => [$message],
            ]);

            return new DataImportRowExecutionOutcome(
                rowNumber: (int) $batchRow->row_number,
                status: DataImportRowStatus::Failed,
                errorMessages: [$message],
            );
        }
    }
}
