<?php

namespace App\Imports;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Mtc\MercuryDataModels\SeoData;

class SeoDataImport implements ToModel, WithHeadingRow
{
    private const UPDATABLE_FIELDS = [
        'title',
        'description',
        'heading',
        'canonical',
        'json_schema',
        'content_description',
    ];

    public function model(array $row): Model|array|null
    {
        try {
            $update = array_intersect_key($row, array_flip(self::UPDATABLE_FIELDS));

            return SeoData::query()
                ->updateOrCreate([
                    'path' => $row['path'],
                ], $update);
        } catch (\Exception $exception) {
            Log::debug('Failed to import row for ' . $row['path'] . ' with exception: ' . $exception->getMessage());
            return null;
        }
    }
}
