<?php

namespace App\Imports\Blog;

use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Mtc\MercuryDataModels\User;

class BlogAuthorResolver
{
    public function resolveByName(?string $fullName): ?int
    {
        $name = trim((string) $fullName);
        if ($name === '') {
            return null;
        }

        $tenantId = tenant('id');
        if (empty($tenantId)) {
            return null;
        }

        $existing = User::query()
            ->whereRaw('LOWER(name) = ?', [mb_strtolower($name)])
            ->whereHas('tenants', fn ($query) => $query->where('tenants.id', $tenantId))
            ->first();

        if ($existing) {
            return $existing->id;
        }

        $user = User::create([
            'name' => $name,
            'email' => $this->generateEmail($name),
            'password' => Hash::make(Str::random(64)),
            'is_locked' => true,
        ]);

        $user->tenants()->attach($tenantId);

        return $user->id;
    }

    private function generateEmail(string $name): string
    {
        $slug = Str::slug($name) ?: 'author';

        return $slug . '-' . Str::uuid()->toString() . '@noreply.getautonomy.co.uk';
    }
}
