<?php

namespace Mtc\Core\Concerns;

/**
 * Shared state/country handling for address models.
 *
 * state and country are NOT NULL at the database level. This trait seeds
 * sensible defaults ('' for state, 'GB' for country) and coerces an explicit
 * null (e.g. from a form that omits the county/state field) so an insert can
 * never send NULL and hit "1048 Column 'state' cannot be null" under strict
 * SQL mode.
 *
 * Defaults are applied via Eloquent's trait initializer (called from the model
 * constructor) rather than a $attributes property default, so the values stay
 * defined once here and cannot drift between the address models.
 */
trait HasDefaultAddressFields
{
    /**
     * Seed the NOT NULL address fields. Eloquent calls this automatically for
     * every new model instance (initialize{TraitName}).
     */
    public function initializeHasDefaultAddressFields(): void
    {
        $this->attributes['state'] = $this->attributes['state'] ?? '';
        $this->attributes['country'] = $this->attributes['country'] ?? 'GB';
    }

    /**
     * state is NOT NULL; coerce a null value to an empty string.
     */
    public function setStateAttribute($value): void
    {
        $this->attributes['state'] = $value ?? '';
    }

    /**
     * country is NOT NULL and should never be null; coerce null to 'GB'.
     */
    public function setCountryAttribute($value): void
    {
        $this->attributes['country'] = $value ?? 'GB';
    }
}
