<?php

namespace App\Imports;

use App\Models\Niveau;
use App\Models\Cycle;
use Illuminate\Support\Facades\Log;

class NiveauImport extends BaseImport
{
    protected $modelClass = Niveau::class;

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

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

            $niveau = new Niveau([
                'libelle' => $this->normalizeText($row['libelle'] ?? ''),
                'cycle_id' => $this->resolveRelationship($row['cycle_id'] ?? null, Cycle::class, 'libelle'),
            ]);

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

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

    public function rules(): array
    {
        return [
            'libelle' => 'required|string|max:255|unique:niveaux,libelle',
            'cycle_id' => 'required|string',
        ];
    }

    public function customValidationMessages(): array
    {
        return [
            'libelle.required' => 'Le libellé est obligatoire',
            'libelle.unique' => 'Ce libellé existe déjà',
            'cycle_id.required' => 'Le cycle est obligatoire',
        ];
    }
}
