<?php

namespace App\Services;

use App\Models\User;
use InvalidArgumentException;

class MemberCodeService
{
    public function generateMemberCode(): string
    {
        return $this->generateForColumn('member_code');
    }

    public function generateReferralCode(): string
    {
        return $this->generateForColumn('referral_code');
    }

    public function generateForColumn(string $column): string
    {
        if (! in_array($column, ['member_code', 'referral_code'], true)) {
            throw new InvalidArgumentException("Unsupported member code column: {$column}");
        }

        do {
            $candidate = 'LW'.str_pad((string) random_int(0, 9999999), 7, '0', STR_PAD_LEFT);
        } while (User::query()->where($column, $candidate)->exists());

        return $candidate;
    }
}
