<?php

declare(strict_types=1);

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\DataImportValueParser;
use App\Models\DberpDataImportBatch;
use App\Models\DberpDataImportBatchRow;
use App\Models\DberpProductBrand;
use Illuminate\Support\Facades\DB;

final class ProductBrandImportHandler extends AbstractMasterDataImportHandler implements DataImportHandler
{
    public function importType(): DataImportType
    {
        return DataImportType::ProductBrand;
    }

    /**
     * @param  list<DataImportRow>  $rows
     */
    public function precheckRows(array $rows): DataImportPrecheckResult
    {
        $outcomes = $this->buildInitialOutcomes($rows);
        $brandCodesInFile = [];
        $namesInFile = [];

        foreach ($rows as $row) {
            $name = DataImportValueParser::trimmed($row->value('name'));
            $brandCode = DataImportValueParser::trimmed($row->value('brand_code'));
            $errors = [];

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

            if ($brandCode !== null) {
                $brandCodesInFile[] = $brandCode;
            }

            if ($name !== null) {
                $namesInFile[] = $name;
            }

            try {
                DataImportValueParser::parseBoolean($row->value('is_enabled'), true);
                DataImportValueParser::parseSortOrder($row->value('sort_order'), 0);
            } catch (\InvalidArgumentException $exception) {
                $errors[] = DataImportValueParser::rowError($row->rowNumber, $exception->getMessage());
            }

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

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

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

        $existingBrandCodes = $this->loadExistingValues(
            DberpProductBrand::class,
            'brand_code',
            array_values(array_unique($brandCodesInFile)),
        );

        $existingNames = $this->loadExistingValues(
            DberpProductBrand::class,
            'name',
            array_values(array_unique($namesInFile)),
        );

        foreach ($rows as $row) {
            $brandCode = DataImportValueParser::trimmed($row->value('brand_code'));
            $name = DataImportValueParser::trimmed($row->value('name'));
            $errors = [];

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

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

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

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

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

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

    private function importRow(DberpDataImportBatchRow $batchRow): DataImportRowExecutionOutcome
    {
        $snapshot = is_array($batchRow->raw_snapshot) ? $batchRow->raw_snapshot : [];

        try {
            $brand = DberpProductBrand::query()->create([
                'brand_code' => DataImportValueParser::trimmed($snapshot['brand_code'] ?? null),
                'name' => (string) DataImportValueParser::trimmed($snapshot['name'] ?? null),
                'is_enabled' => DataImportValueParser::parseBoolean($snapshot['is_enabled'] ?? null, true),
                'sort_order' => DataImportValueParser::parseSortOrder($snapshot['sort_order'] ?? null, 0),
            ]);

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

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