<?php

declare(strict_types=1);

namespace App\Business\DataImport;

use App\Business\DataImport\Enums\DataImportBatchStatus;
use App\Models\DberpDataImportBatch;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;

final class DataImportBatchDeletionService
{
    public function __construct(
        private readonly DataImportAuditLogger $auditLogger,
    ) {}

    public function canDelete(DberpDataImportBatch $batch): bool
    {
        return ! in_array($batch->status, [
            DataImportBatchStatus::Pending,
            DataImportBatchStatus::Processing,
        ], true);
    }

    public function delete(DberpDataImportBatch $batch): void
    {
        if (! $this->canDelete($batch)) {
            throw ValidationException::withMessages([
                'batch' => (string) __('dberp.data_import.errors.batch_delete_not_allowed'),
            ]);
        }

        $this->deleteStoredFile($batch);
        $this->auditLogger->logDeleted($batch);
        $batch->delete();
    }

    private function deleteStoredFile(DberpDataImportBatch $batch): void
    {
        $storedPath = $batch->stored_path;

        if (! is_string($storedPath) || $storedPath === '') {
            return;
        }

        Storage::disk('local')->delete($storedPath);
    }
}
