<?php

namespace App\Imports;

use App\Models\Etablissement;
use App\Models\Cycle;
use App\Models\Commune;
use Illuminate\Support\Facades\Log;

class EtablissementImport extends BaseImport
{
    protected $modelClass = Etablissement::class;

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

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

            $etablissement = new Etablissement([
                'libellear' => $this->normalizeText($row['libellear'] ?? ''),
                'libellefr' => $this->normalizeText($row['libellefr'] ?? ''),
                'cycle_id' => $this->resolveRelationship($row['cycle_id'] ?? null, Cycle::class, 'libelle'),
                'code' => $this->normalizeText($row['code'] ?? ''),
                'latitude' => $this->normalizeText($row['latitude'] ?? null),
                'longitude' => $this->normalizeText($row['longitude'] ?? null),
                'etat' => $this->normalizeText($row['etat'] ?? ''),
                'commune_id' => $this->resolveRelationship($row['commune_id'] ?? null, Commune::class, 'libelle'),
            ]);

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

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

    public function rules(): array
    {
        return [
            'libellear' => 'required|string|max:255',
            'libellefr' => 'required|string|max:255',
            'cycle_id' => 'required|string',
            'code' => 'required|string|max:255|unique:etablissements,code',
            'commune_id' => 'required|string',
        ];
    }

    public function customValidationMessages(): array
    {
        return [
            'libellear.required' => 'Le libellé en arabe est obligatoire',
            'libellefr.required' => 'Le libellé en français est obligatoire',
            'cycle_id.required' => 'Le cycle est obligatoire',
            'code.required' => 'Le code est obligatoire',
            'code.unique' => 'Ce code existe déjà',
            'commune_id.required' => 'La commune est obligatoire',
        ];
    }
}
