<?php

declare(strict_types=1);

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;
    }
}
