<?php

namespace App\Models;

use App\Enums\RecordStatus;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class DocumentType extends Model
{
    protected $fillable = [
        'name', 'slug', 'description', 'is_required',
        'allowed_mimes', 'max_size_kb', 'status', 'sort_order',
    ];

    protected function casts(): array
    {
        return [
            'is_required' => 'boolean',
            'allowed_mimes' => 'array',
            'status' => RecordStatus::class,
        ];
    }

    public function documents(): HasMany
    {
        return $this->hasMany(Document::class);
    }

    public function scopeActive(Builder $query): Builder
    {
        return $query->where('status', RecordStatus::Active);
    }

    public function scopeRequired(Builder $query): Builder
    {
        return $query->active()->where('is_required', true);
    }

    public function scopeOrdered(Builder $query): Builder
    {
        return $query->orderBy('sort_order')->orderBy('name');
    }

    public function maxSizeKb(): int
    {
        return $this->max_size_kb ?? (int) config('kcu.documents.max_size_kb');
    }

    public function allowedMimes(): array
    {
        return $this->allowed_mimes ?: config('kcu.documents.allowed_mimes');
    }

    public function acceptAttribute(): string
    {
        return collect($this->allowedMimes())->map(fn ($e) => ".{$e}")->implode(',');
    }
}
