<?php

namespace App\Imports;

use App\Models\Reforme;
use Illuminate\Support\Facades\Log;

class ReformeImport extends BaseImport
{
    protected $modelClass = Reforme::class;

    public function model(array $row)
    {
        try {
            $this->validateRow($row);

            // Check for duplicate by libelle
            if ($this->handleDuplicate($row, 'libelle')) {
                return null;
            }

            $reforme = new Reforme([
                'libelle' => $this->normalizeText($row['libelle'] ?? ''),
                'description' => $this->normalizeText($row['description'] ?? ''),
                'date_debut' => $this->formatDate($row['date_debut'] ?? null),
                'date_fin' => $this->formatDate($row['date_fin'] ?? null),
            ]);

            $this->results['success_count']++;
            $this->logInfo('Reforme imported successfully', ['libelle' => $row['libelle'] ?? null]);

            return $reforme;
        } catch (\Exception $e) {
            $this->results['error_count']++;
            $this->results['errors'][] = [
                'row' => $row,
                'error' => $e->getMessage(),
            ];
            $this->logError('Reforme import failed', [
                'error' => $e->getMessage(),
                'row' => $row,
            ]);
            return null;
        }
    }

    public function rules(): array
    {
        return [
            'libelle' => 'required|string|max:255|unique:reformes,libelle',
            'description' => 'nullable|string',
            'date_debut' => 'required|date',
            'date_fin' => 'nullable|date|after:date_debut',
        ];
    }

    public function customValidationMessages(): array
    {
        return [
            'libelle.required' => 'Le libellé est obligatoire',
            'libelle.unique' => 'Ce libellé existe déjà',
            'date_debut.required' => 'La date de début est obligatoire',
            'date_fin.after' => 'La date de fin doit être après la date de début',
        ];
    }
}
