<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

#[Fillable([
    'name',
    'display_name',
    'description',
    'visibility',
    'max_file_size',
    'allowed_mime_types',
    'is_active',
    'created_by',
])]
class FileBucket extends Model
{
    /** @use HasFactory<\Database\Factories\FileBucketFactory> */
    use HasFactory;

    /**
     * Get the user who created this bucket.
     */
    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Get all files in this bucket.
     */
    public function files(): HasMany
    {
        return $this->hasMany(File::class, 'bucket_id');
    }

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'allowed_mime_types' => 'array',
            'is_active' => 'boolean',
            'max_file_size' => 'integer',
        ];
    }

    /**
     * Check if a MIME type is allowed for this bucket.
     */
    public function allowsMimeType(string $mimeType): bool
    {
        if (empty($this->allowed_mime_types)) {
            return true;
        }

        return in_array($mimeType, $this->allowed_mime_types);
    }

    /**
     * Get the effective max file size (bucket override or global default).
     */
    public function getEffectiveMaxFileSize(): int
    {
        return $this->max_file_size ?? config('file_upload.max_file_size', 104857600);
    }
}
