<?php

namespace App\Models;

use App\Traits\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;

class NumberingRule extends Model
{
    use BelongsToTenant;

    protected $fillable = [
        'tenant_id',
        'document_type',
        'rule_name',
        'pattern',
        'reset_period',
        'sequence_padding',
        'is_active',
        'created_by',
        'updated_by',
    ];

    protected $casts = [
        'pattern' => 'array',
        'is_active' => 'boolean',
        'sequence_padding' => 'integer',
    ];

    // SoftDeletes 없음 (DB에 deleted_at 컬럼 없음) → Hard Delete

    const DOC_QUOTE = 'quote';

    const DOC_ORDER = 'order';

    const DOC_SALE = 'sale';

    const DOC_WORK_ORDER = 'work_order';

    const DOC_MATERIAL_RECEIPT = 'material_receipt';

    public static function documentTypes(): array
    {
        return [
            self::DOC_QUOTE => '견적',
            self::DOC_ORDER => '수주',
            self::DOC_SALE => '매출',
            self::DOC_WORK_ORDER => '작업지시',
            self::DOC_MATERIAL_RECEIPT => '원자재수입검사',
        ];
    }

    public static function resetPeriods(): array
    {
        return [
            'daily' => '일별',
            'monthly' => '월별',
            'yearly' => '연별',
            'never' => '리셋안함',
        ];
    }

    public function getPreviewAttribute(): string
    {
        if (empty($this->pattern) || ! is_array($this->pattern)) {
            return '';
        }

        $result = '';
        foreach ($this->pattern as $segment) {
            $result .= match ($segment['type'] ?? '') {
                'static' => $segment['value'] ?? '',
                'separator' => $segment['value'] ?? '',
                'date' => now()->format($segment['format'] ?? 'ymd'),
                'param' => $segment['default'] ?? '{'.($segment['key'] ?? '?').'}',
                'mapping' => $segment['default'] ?? '{'.($segment['key'] ?? '?').'}',
                'sequence' => str_pad('1', $this->sequence_padding, '0', STR_PAD_LEFT),
                default => '',
            };
        }

        return $result;
    }

    public function getDocumentTypeLabelAttribute(): string
    {
        return self::documentTypes()[$this->document_type] ?? $this->document_type;
    }

    public function getResetPeriodLabelAttribute(): string
    {
        return self::resetPeriods()[$this->reset_period] ?? $this->reset_period;
    }
}
