<?php

namespace App\Services\Showroom;

use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

class ShowroomCustomerService
{
    public function findByMobile(string $mobile): ?User
    {
        $normalized = $this->normalizeMobile($mobile);

        return User::query()
            ->when(Schema::hasColumn('users', 'phone_normalized'), function ($query) use ($normalized) {
                $query->orWhere('phone_normalized', $normalized);
            })
            ->orWhere('phone', $mobile)
            ->orWhereRaw('REPLACE(REPLACE(REPLACE(REPLACE(phone, "+", ""), " ", ""), "-", ""), ".", "") = ?', [$normalized])
            ->first();
    }

    public function findOrCreateByMobile(string $mobile, ?string $name = null): User
    {
        $normalized = $this->normalizeMobile($mobile);
        if ($normalized === '') {
            throw ValidationException::withMessages([
                'mobile' => translate('Customer mobile number is required.'),
            ]);
        }

        return DB::transaction(function () use ($mobile, $name, $normalized) {
            $existing = $this->findByMobile($mobile);
            if ($existing) {
                if (Schema::hasColumn('users', 'phone_normalized') && blank($existing->phone_normalized)) {
                    $existing->phone_normalized = $normalized;
                    $existing->save();
                }
                return $existing;
            }

            $name = trim((string) ($name ?: $mobile));
            $parts = preg_split('/\s+/', $name, 2);
            $payload = [
                'name' => $name,
                'f_name' => $parts[0] ?? $name,
                'l_name' => $parts[1] ?? '',
                'phone' => $mobile,
                'email' => null,
                'password' => Hash::make(Str::random(24)),
                'wallet_balance' => 0,
                'loyalty_point' => 0,
            ];

            if (Schema::hasColumn('users', 'phone_normalized')) {
                $payload['phone_normalized'] = $normalized;
            }

            return User::create($payload);
        });
    }

    public function normalizeMobile(string $mobile): string
    {
        return preg_replace('/\D+/', '', $mobile) ?: '';
    }
}
