<?php

namespace App\Filament\Imports;

use App\Models\Company;
use App\Models\Plant;
use Filament\Actions\Imports\Exceptions\RowImportFailedException;
use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import;
use Str;

class PlantImporter extends Importer
{
    protected static ?string $model = Plant::class;

    public static function getColumns(): array
    {
        return [
            ImportColumn::make('code')
                ->requiredMapping()
                ->numeric()
                ->exampleHeader('Plant Code')
                ->example('1000')
                ->label('Plant Code')
                ->rules(['required']), //, 'integer'
            ImportColumn::make('name')
                ->requiredMapping()
                ->exampleHeader('Plant Name')
                ->example('Ransar Industries-I')
                ->label('Plant Name')
                ->rules(['required']),
            ImportColumn::make('address')
                ->requiredMapping()
                ->exampleHeader('Plant Address')
                ->example('7/51-A, Keeranatham Road, Saravanampatty, Coimbatore - 641035')
                ->label('Plant Address')
                ->rules(['required']),
            ImportColumn::make('company')
                ->requiredMapping()
                ->exampleHeader('Company Name')
                ->example('C.R.I. Pumps Private Limited')
                ->label('Company Name')
                ->relationship(resolveUsing:'name')
                ->rules(['required']),
        ];
    }

    public function resolveRecord(): ?Plant
    {
        $warnMsg = [];
        $company = Company::where('name', $this->data['company'])->first();
        if (!$company) {
            $warnMsg[] = "Company name not found";
        }
        if (Str::length($this->data['name']) < 0) {
            $warnMsg[] = "Plant name not found";
        }
        if (Str::length($this->data['code']) < 4 || !is_numeric($this->data['code']) || !preg_match('/^[1-9]\d{3,}$/', $this->data['code'])) {
            $warnMsg[] = "Invalid plant code found";
        }
        if (Str::length($this->data['address']) < 3) {
            $warnMsg[] = "Invalid address found";
        }
        if (!empty($warnMsg)) {
            throw new RowImportFailedException(implode(', ', $warnMsg));
        }

        $plantCN = Plant::where('code', $this->data['code'])->where('name', $this->data['name'])->first();
        if (!$plantCN) {
            $plantCode = Plant::where('code', $this->data['code'])->first();
            $plantName = Plant::where('name', $this->data['name'])->first();
            if ($plantName) {
                throw new RowImportFailedException("Duplicate plant name found");
            }
            else if ($plantCode) {
                throw new RowImportFailedException("Duplicate plant code found");
            }
        }

        return Plant::updateOrCreate([
                'code' => $this->data['code'],
                'name' => $this->data['name'],
            ],
            [
                'address' => $this->data['address'],
                'company_id' => $company->id
            ]
        );
        // return Plant::firstOrNew([
        //     // Update existing records, matching them by `$this->data['column_name']`
        //     'email' => $this->data['email'],
        // ]);

        // return new Plant();
    }

    public static function getCompletedNotificationBody(Import $import): string
    {
        $body = 'Your plant 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;
    }
}
