<?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\DataImportRow;
use App\Business\DataImport\DataImportRowExecutionOutcome;
use App\Business\DataImport\DataImportRowPrecheckOutcome;
use App\Business\DataImport\Enums\DataImportRowStatus;
use App\Business\DataImport\Enums\DataImportType;
use App\Business\DataImport\Support\DataImportReferenceResolver;
use App\Business\DataImport\Support\DataImportValueParser;
use App\Models\DberpDataImportBatch;
use App\Models\DberpDataImportBatchRow;
use App\Models\DberpRegion;
use App\Models\DberpWarehouse;
use Illuminate\Support\Facades\DB;

final class WarehouseImportHandler extends AbstractMasterDataImportHandler implements DataImportHandler
{
    public function __construct(
        private readonly DataImportReferenceResolver $referenceResolver,
    ) {}

    public function importType(): DataImportType
    {
        return DataImportType::Warehouse;
    }

    /**
     * @param  list<DataImportRow>  $rows
     */
    public function precheckRows(array $rows): DataImportPrecheckResult
    {
        $outcomes = $this->buildInitialOutcomes($rows);
        $codesInFile = [];
        $managerCodesInFile = [];
        $regionCodesInFile = [];
        /** @var list<int> $defaultRowNumbers */
        $defaultRowNumbers = [];

        foreach ($rows as $row) {
            $name = DataImportValueParser::trimmed($row->value('name'));
            $code = DataImportValueParser::trimmed($row->value('code'));
            $managerCode = DataImportValueParser::trimmed($row->value('manager_employee_code'));
            $regionCode = DataImportValueParser::trimmed($row->value('region_code'));
            $errors = [];

            if ($name === null) {
                $errors[] = DataImportValueParser::rowError($row->rowNumber, (string) __('dberp.data_import.validation.name_required'));
            }

            if ($code !== null) {
                $codesInFile[] = $code;
            }

            if ($managerCode !== null) {
                $managerCodesInFile[] = $managerCode;
            }

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

            try {
                DataImportValueParser::parseWarehouseType($row->value('warehouse_type'));
                DataImportValueParser::parseBoolean($row->value('is_default'), false);
                DataImportValueParser::parseBoolean($row->value('is_enabled'), true);
                DataImportValueParser::parseSortOrder($row->value('sort_order'), 0);

                if (DataImportValueParser::parseBoolean($row->value('is_default'), false)) {
                    $defaultRowNumbers[] = $row->rowNumber;
                }
            } catch (\InvalidArgumentException $exception) {
                $errors[] = DataImportValueParser::rowError($row->rowNumber, $exception->getMessage());
            }

            if ($errors !== []) {
                $outcomes = $this->markRowFailed($outcomes, $row->rowNumber, $errors);
            }
        }

        if (count($defaultRowNumbers) > 1) {
            foreach ($defaultRowNumbers as $rowNumber) {
                $outcomes = $this->markRowFailed($outcomes, $rowNumber, [
                    DataImportValueParser::rowError($rowNumber, (string) __('dberp.data_import.validation.multiple_default_warehouses_in_file')),
                ]);
            }
        }

        $outcomes = $this->applyDuplicateFieldErrors(
            $rows,
            $outcomes,
            'code',
            'dberp.data_import.validation.code_duplicate_in_file',
        );

        $existingCodes = $this->loadExistingValues(
            DberpWarehouse::class,
            'code',
            array_values(array_unique($codesInFile)),
        );

        $employeeIdsByCode = $this->referenceResolver->employeeIdsByCodes(array_values(array_unique($managerCodesInFile)));
        $regionsByCode = $this->referenceResolver->regionsByCodes(array_values(array_unique($regionCodesInFile)));

        foreach ($rows as $row) {
            $code = DataImportValueParser::trimmed($row->value('code'));
            $managerCode = DataImportValueParser::trimmed($row->value('manager_employee_code'));
            $regionCode = DataImportValueParser::trimmed($row->value('region_code'));
            $errors = [];

            if ($code !== null && in_array($code, $existingCodes, true)) {
                $errors[] = DataImportValueParser::rowError($row->rowNumber, (string) __('dberp.data_import.validation.code_exists_in_database', [
                    'value' => $code,
                ]));
            }

            if ($managerCode !== null && ! isset($employeeIdsByCode[$managerCode])) {
                $errors[] = DataImportValueParser::rowError($row->rowNumber, (string) __('dberp.data_import.validation.invalid_manager_employee_code', [
                    'value' => $managerCode,
                ]));
            }

            if ($regionCode !== null && ! isset($regionsByCode[$regionCode])) {
                $errors[] = DataImportValueParser::rowError($row->rowNumber, (string) __('dberp.data_import.validation.invalid_region_code', [
                    'value' => $regionCode,
                ]));
            }

            if ($errors !== []) {
                $outcomes = $this->markRowFailed($outcomes, $row->rowNumber, $errors);
            }
        }

        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();

        $managerCodes = [];
        $regionCodes = [];

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

            if ($managerCode !== null) {
                $managerCodes[] = $managerCode;
            }

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

        $employeeIdsByCode = $this->referenceResolver->employeeIdsByCodes(array_values(array_unique($managerCodes)));
        $regionsByCode = $this->referenceResolver->regionsByCodes(array_values(array_unique($regionCodes)));

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

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

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

    /**
     * @param  array<string, int>  $employeeIdsByCode
     * @param  array<string, DberpRegion>  $regionsByCode
     */
    private function importRow(
        DberpDataImportBatchRow $batchRow,
        array $employeeIdsByCode,
        array $regionsByCode,
    ): DataImportRowExecutionOutcome {
        $snapshot = is_array($batchRow->raw_snapshot) ? $batchRow->raw_snapshot : [];
        $managerCode = DataImportValueParser::trimmed($snapshot['manager_employee_code'] ?? null);
        $regionCode = DataImportValueParser::trimmed($snapshot['region_code'] ?? null);

        try {
            $payload = [
                'code' => DataImportValueParser::trimmed($snapshot['code'] ?? null),
                'name' => (string) DataImportValueParser::trimmed($snapshot['name'] ?? null),
                'warehouse_type' => DataImportValueParser::parseWarehouseType($snapshot['warehouse_type'] ?? null),
                'is_default' => DataImportValueParser::parseBoolean($snapshot['is_default'] ?? null, false),
                'is_enabled' => DataImportValueParser::parseBoolean($snapshot['is_enabled'] ?? null, true),
                'sort_order' => DataImportValueParser::parseSortOrder($snapshot['sort_order'] ?? null, 0),
                'address' => DataImportValueParser::trimmed($snapshot['address'] ?? null),
                'remark' => DataImportValueParser::trimmed($snapshot['remark'] ?? null),
                'manager_employee_id' => $managerCode !== null ? ($employeeIdsByCode[$managerCode] ?? null) : null,
                'country_code' => null,
                'region_id' => null,
                'region_name_snapshot' => null,
            ];

            if ($regionCode !== null) {
                $region = $regionsByCode[$regionCode] ?? null;

                if ($region === null) {
                    throw new \RuntimeException((string) __('dberp.data_import.validation.invalid_region_code', [
                        'value' => $regionCode,
                    ]));
                }

                $payload['country_code'] = $region->country_code;
                $payload['region_id'] = (int) $region->getKey();
                $payload['region_name_snapshot'] = $region->merger_name;
            }

            $warehouse = DberpWarehouse::query()->create($payload);

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

            return new DataImportRowExecutionOutcome(
                rowNumber: (int) $batchRow->row_number,
                status: DataImportRowStatus::Imported,
                createdRecordType: DberpWarehouse::class,
                createdRecordId: (int) $warehouse->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],
            );
        }
    }

    /**
     * @param  list<DataImportRowPrecheckOutcome>  $outcomes
     */
    private function buildPrecheckResult(array $outcomes): DataImportPrecheckResult
    {
        $validatedCount = 0;
        $failedCount = 0;

        foreach ($outcomes as $outcome) {
            if ($outcome->passed()) {
                $validatedCount++;
            } else {
                $failedCount++;
            }
        }

        return new DataImportPrecheckResult($outcomes, $validatedCount, $failedCount);
    }
}
