<?php

namespace App\Filament\Imports;

use App\Models\StickerPrinting;
use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import;
use Filament\Actions\Imports\Exceptions\RowImportFailedException;
use App\Models\Plant;
use App\Models\User;
use Str;
use Filament\Facades\Filament;

class StickerPrintingImporter extends Importer
{
    protected static ?string $model = StickerPrinting::class;

    public static function getColumns(): array
    {
        return [
            ImportColumn::make('plant')
                ->requiredMapping()
                ->exampleHeader('PLANT CODE')
                ->example('1000')
                ->label('PLANT CODE')
                ->relationship(resolveUsing: 'code')
                ->rules(['required']),
            ImportColumn::make('reference_number')
                ->exampleHeader('REFERENCE NUMBER')
                ->example('REF123456')
                ->label('REFERENCE NUMBER'),
            ImportColumn::make('serial_number')
                ->exampleHeader('SERIAL NUMBER')
                ->example('135245325212')
                ->label('SERIAL NUMBER'),
            // ImportColumn::make('created_by')
            //     ->exampleHeader('CREATED BY')
            //     ->example('RAW01234')
            //     ->label('CREATED BY'),
        ];
    }

    public function resolveRecord(): ?StickerPrinting
    {
        // return StickerPrinting::firstOrNew([
        //     // Update existing records, matching them by `$this->data['column_name']`
        //     'email' => $this->data['email'],
        // ]);

        $warnMsg = [];
        $plant = Plant::where('code', $this->data['plant'])->first();

        if (Str::length($this->data['serial_number']) < 9 || !ctype_alnum($this->data['serial_number'])) {
            $warnMsg[] = "Invalid serial number found";
        }

        $existing = StickerPrinting::where('plant_id', $plant->id)
            ->where('serial_number', $this->data['serial_number'])
            ->first();

        if ($existing) {
            $warnMsg[] = "Serial number already exists for this plant!";//throw new RowImportFailedException("Serial number already exists for this plant!");
        }

        $serial = $this->data['serial_number'];

        // --- Check duplicate in DB ---
        $existsInDB = StickerPrinting::where('plant_id', $plant->id)
            ->where('serial_number', $serial)
            ->first();

        if ($existsInDB) {
            //throw new RowImportFailedException("Serial number '{$serial}' already exists in DB for this plant!");
            $warnMsg[] = "Serial number '{$serial}' already exists in DB for this plant!";
        }

        if (!empty($warnMsg)) {
            throw new RowImportFailedException(implode(', ', $warnMsg));
        }

        StickerPrinting::Create([
            'plant_id' => $plant->id,
            'reference_number' => $this->data['reference_number'],
            'serial_number' => $this->data['serial_number'],
            'created_at' => now(),
            'updated_at' =>now(),
            'created_by' => Filament::auth()->user()?->name,
        ]);

        return null;

        //return new StickerPrinting();
    }

    public static function getCompletedNotificationBody(Import $import): string
    {
        $body = 'Your sticker printing import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.';

        if ($failedRowsCount = $import->getFailedRowsCount()) {
            $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.';
        }

        return $body;
    }
}
