<?php

namespace App\Imports;

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

class VolumeHoraireImport extends BaseImport
{
    protected $modelClass = VolumeHoraire::class;

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

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

            $volumeHoraire = new VolumeHoraire([
                'libelle' => $this->normalizeText($row['libelle'] ?? ''),
                'volume_horaire' => (int) ($row['volume_horaire'] ?? 0),
            ]);

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

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

    public function rules(): array
    {
        return [
            'libelle' => 'required|string|max:255|unique:volume_horaires,libelle',
            'volume_horaire' => 'required|numeric|min:0',
        ];
    }

    public function customValidationMessages(): array
    {
        return [
            'libelle.required' => 'Le libellé est obligatoire',
            'libelle.unique' => 'Ce libellé existe déjà',
            'volume_horaire.required' => 'Le volume horaire est obligatoire',
            'volume_horaire.min' => 'Le volume horaire doit être positif',
        ];
    }
}
