<?php

namespace App\Imports;

use Illuminate\Database\Eloquent\Model;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Mtc\MercuryDataModels\SeoRedirect;

class SeoRedirectImport implements ToModel, WithHeadingRow
{
    public function model(array $row): Model|array|null
    {
        $row['from'] = rtrim($row['from'] ?? '', '/');
        $isGone = (int) ($row['code'] ?? 0) === 410;
        $row['to'] = $isGone ? null : rtrim($row['to'] ?? '', '/');
        if ($this->conflictingRedirect($row)) {
            return null;
        }

        return SeoRedirect::query()
            ->updateOrCreate([
                'from' => $row['from'],
                'from_domain' => $row['from_domain'] ?? null,
            ], [
                'to' => $row['to'],
                'code' => $row['code'],
                'to_domain' => $row['to_domain'] ?? null,
                'has_regex' => $row['has_regex'] ?? 0
            ]);
    }

    private function conflictingRedirect(array $row): bool
    {
        if ($row['to'] === null) {
            return false;
        }
        $redirect_to_itself = $row['from'] === $row['to']
            && ($row['from_domain'] === $row['to_domain'] || empty($row['to_domain']));
        if ($redirect_to_itself) {
            return true;
        }
        return SeoRedirect::query()->where('from', $row['to'])->exists();
    }
}
