<?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 Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

abstract class AbstractPartnerCategoryImportHandler extends AbstractMasterDataImportHandler implements DataImportHandler
{
    /**
     * @return class-string<Model>
     */
    abstract protected function categoryModelClass(): string;

    abstract public function importType(): DataImportType;

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

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

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

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

            try {
                DataImportValueParser::parseMasterRecordStatus($row->value('status'));
                DataImportValueParser::parseSort($row->value('sort'));
            } catch (\InvalidArgumentException $exception) {
                $errors[] = DataImportValueParser::rowError($row->rowNumber, $exception->getMessage());
            }

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

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

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

        foreach ($rows as $row) {
            $code = DataImportValueParser::trimmed($row->value('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 ($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();

        $modelClass = $this->categoryModelClass();

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

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

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

    /**
     * @param  class-string<Model>  $modelClass
     */
    private function importRow(DberpDataImportBatchRow $batchRow, string $modelClass): DataImportRowExecutionOutcome
    {
        $snapshot = is_array($batchRow->raw_snapshot) ? $batchRow->raw_snapshot : [];

        try {
            /** @var Model $record */
            $record = $modelClass::query()->create([
                'code' => DataImportValueParser::trimmed($snapshot['code'] ?? null),
                'name' => (string) DataImportValueParser::trimmed($snapshot['name'] ?? null),
                'status' => DataImportValueParser::parseMasterRecordStatus($snapshot['status'] ?? null),
                'sort' => DataImportValueParser::parseSort($snapshot['sort'] ?? null),
                'remark' => DataImportValueParser::trimmed($snapshot['remark'] ?? null),
            ]);

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

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