<?php

namespace App\Models\Concerns;

use App\Models\Business;
use App\Support\PhoneNumber;
use Illuminate\Database\Eloquent\Model;
use InvalidArgumentException;

trait NormalizesPhoneNumbers
{
    public static function bootNormalizesPhoneNumbers(): void
    {
        static::saving(function (Model $model): void {
            $countryCode = $model instanceof Business && filled($model->getAttribute('phone_country_code'))
                ? PhoneNumber::sanitizeCountryCode($model->getAttribute('phone_country_code'))
                : PhoneNumber::countryCode();

            foreach ($model->phoneNumberAttributes() as $attribute) {
                if (! $model->isDirty($attribute)) {
                    continue;
                }

                $value = $model->getAttribute($attribute);
                if ($value === null || trim((string) $value) === '') {
                    $model->setAttribute($attribute, null);
                    continue;
                }

                $normalized = PhoneNumber::normalize($value, $countryCode);
                if ($normalized === null) {
                    throw new InvalidArgumentException("Invalid phone number supplied for {$attribute}.");
                }

                $model->setAttribute($attribute, $normalized);
            }
        });
    }

    protected function phoneNumberAttributes(): array
    {
        return ['phone'];
    }
}
