<?php

namespace App\Services;

use App\Models\Coupon;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Support\Str;

class CouponService
{
    public function findOrCreateForPhone(string $phone): Coupon
    {
        $existing = Coupon::query()->where('phone', $phone)->first();

        if ($existing) {
            return $existing;
        }

        return $this->createWithUniqueCode($phone);
    }

    private function createWithUniqueCode(string $phone): Coupon
    {
        for ($attempt = 0; $attempt < 10; $attempt++) {
            try {
                return Coupon::query()->create([
                    'phone' => $phone,
                    'code' => $this->generateCouponCode(),
                ]);
            } catch (UniqueConstraintViolationException) {
                continue;
            }
        }

        throw new \RuntimeException('Unable to generate a unique coupon code.');
    }

    private function generateCouponCode(): string
    {
        $x = random_int(1, 9);
        $yyyy = Str::upper(Str::random(4));

        return "{$x}_{$yyyy}";
    }
}
