<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\User;
use App\Support\UsernamePolicy;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

final class UsernameApprovalService
{
    public function submit(?User $user, string $username, string $context, array $payload = []): ?int
    {
        if (! Schema::hasTable('username_approval_requests')) {
            return null;
        }

        $normalized = UsernamePolicy::normalize($username);
        $similar = UsernamePolicy::similarReserved($normalized);
        if ($similar === null) {
            return null;
        }

        $existingId = DB::table('username_approval_requests')
            ->where('requested_username', $normalized)
            ->where('context', $context)
            ->where('status', 'pending')
            ->when($user !== null, fn ($q) => $q->where('user_id', (int) $user->id), fn ($q) => $q->whereNull('user_id'))
            ->value('id');

        if ($existingId) {
            return (int) $existingId;
        }

        return (int) DB::table('username_approval_requests')->insertGetId([
            'user_id' => $user?->id,
            'requested_username' => $normalized,
            'context' => $context,
            'similar_to' => $similar,
            'status' => 'pending',
            'payload' => $payload === [] ? null : json_encode($payload),
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }
}
