<?php

declare(strict_types=1);

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

namespace App\Models;

use App\Business\MasterData\DberpRegionSource;
use App\Business\MasterData\Enums\RegionLevel;
use App\Models\Concerns\HasDberpAuditTrail;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class DberpRegion extends Model
{
    use HasDberpAuditTrail;

    protected $table = 'dberp_regions';

    /**
     * @var list<string>
     */
    protected $fillable = [
        'parent_id',
        'country_code',
        'region_code',
        'external_code',
        'name',
        'short_name',
        'level',
        'depth',
        'path',
        'merger_name',
        'remark',
        'sort_order',
        'is_enabled',
        'is_leaf',
        'source',
    ];

    protected function casts(): array
    {
        return [
            'parent_id' => 'integer',
            'depth' => 'integer',
            'sort_order' => 'integer',
            'is_enabled' => 'boolean',
            'is_leaf' => 'boolean',
        ];
    }

    protected static function booted(): void
    {
        static::creating(function (self $region): void {
            if ($region->source === null || $region->source === '') {
                $region->source = DberpRegionSource::Manual;
            }
        });

        static::created(function (self $region): void {
            if ($region->parent_id === null) {
                return;
            }

            self::query()->whereKey($region->parent_id)->update(['is_leaf' => false]);
        });

        static::deleted(function (self $region): void {
            if ($region->parent_id === null) {
                return;
            }

            $parentId = (int) $region->parent_id;

            if (! self::query()->whereKey($parentId)->exists()) {
                return;
            }

            $stillHasChildren = self::query()->where('parent_id', $parentId)->exists();

            self::query()->whereKey($parentId)->update([
                'is_leaf' => ! $stillHasChildren,
            ]);
        });

        static::updating(function (self $region): void {
            $service = app('App\\Business\\MasterData\\DberpRegionGovernanceService');

            if ($region->isDirty('parent_id')) {
                $service->ensureCanChangeParent($region, $region->parent_id === null ? null : (int) $region->parent_id);
            }

            $service->ensureAdminUpdateAllowsDirtyAttributes($region);

            if ($region->isDirty('is_enabled') && $region->is_enabled === false) {
                $service->ensureCanDisable($region);
            }
        });

        static::deleting(function (self $region): void {
            app('App\\Business\\MasterData\\DberpRegionGovernanceService')->ensureCanDelete($region);
        });
    }

    public function getDberpAuditActionPrefix(): string
    {
        return 'dberp.region';
    }

    /**
     * @return list<string>
     */
    public function getDberpAuditFields(): array
    {
        return $this->getFillable();
    }

    public function parent(): BelongsTo
    {
        return $this->belongsTo(self::class, 'parent_id');
    }

    public function children(): HasMany
    {
        return $this->hasMany(self::class, 'parent_id');
    }

    public function customers(): HasMany
    {
        return $this->hasMany(DberpCustomer::class, 'region_id');
    }

    public function suppliers(): HasMany
    {
        return $this->hasMany(DberpSupplier::class, 'region_id');
    }

    public function warehouses(): HasMany
    {
        return $this->hasMany(DberpWarehouse::class, 'region_id');
    }

    public function scopeEnabled(Builder $query): Builder
    {
        return $query->where('is_enabled', true);
    }

    public function scopeForCountry(Builder $query, string $countryCode): Builder
    {
        return $query->where('country_code', $countryCode);
    }

    public function scopeFinalSelectable(Builder $query): Builder
    {
        return $query->where('is_enabled', true)->where('is_leaf', true);
    }

    public function levelLabel(): string
    {
        return RegionLevel::tryFrom((string) $this->level)?->label() ?? __('dberp.options.region_level.other');
    }
}
