<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

namespace App\Filament\Resources\Concerns;

use App\Business\MasterData\DberpRegionAddressService;
use App\Models\DberpRegion;

trait InteractsWithDberpRegionAddress
{
    /**
     * @param  array<string, mixed>  $data
     * @return array<string, mixed>
     */
    protected function mutateDberpRegionFormDataBeforeFill(array $data): array
    {
        /** @var DberpRegionAddressService $service */
        $service = app('App\\Business\\MasterData\\DberpRegionAddressService');

        return $service->fillFormData($data, $this->getCurrentDberpRegion());
    }

    /**
     * @param  array<string, mixed>  $data
     * @return array<string, mixed>
     */
    protected function mutateDberpRegionFormDataBeforePersist(array $data): array
    {
        /** @var DberpRegionAddressService $service */
        $service = app('App\\Business\\MasterData\\DberpRegionAddressService');

        if (! filled($data['country_code'] ?? null)) {
            $existingCountryCode = $this->resolveExistingCountryCodeForAddressPersist();

            if (filled($existingCountryCode)) {
                $data['country_code'] = $existingCountryCode;
            }
        }

        return $service->prepareFormDataForSave(
            $data,
            $this->getCurrentDberpRegion(),
        );
    }

    protected function getCurrentDberpRegion(): ?DberpRegion
    {
        $record = property_exists($this, 'record') ? $this->record : null;

        return $record?->region instanceof DberpRegion ? $record->region : null;
    }

    protected function resolveExistingCountryCodeForAddressPersist(): ?string
    {
        $record = property_exists($this, 'record') ? $this->record : null;

        if ($record !== null && filled($record->getAttribute('country_code'))) {
            return (string) $record->getAttribute('country_code');
        }

        if (method_exists($this, 'resolveSystemProfileRecord')) {
            $profile = $this->resolveSystemProfileRecord();

            if (filled($profile->country_code)) {
                return (string) $profile->country_code;
            }
        }

        return null;
    }
}
