<?php

declare(strict_types=1);

namespace App\Models;

use App\Domain\Media\AttachmentStorageService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Attachment extends Model
{
    public const VISIBILITY_PUBLIC = 'public';

    public const VISIBILITY_PRIVATE = 'private';

    protected $fillable = [
        'article_id',
        'disk',
        'path',
        'thumb_path',
        'filename',
        'mime',
        'size',
        'checksum',
        'visibility',
        'legacy_filepath',
        'synced_at',
        'downloads',
    ];

    protected function casts(): array
    {
        return [
            'size' => 'integer',
            'downloads' => 'integer',
            'synced_at' => 'datetime',
        ];
    }

    public function article(): BelongsTo
    {
        return $this->belongsTo(Article::class);
    }

    protected static function booted(): void
    {
        static::deleting(function (Attachment $attachment): void {
            app(AttachmentStorageService::class)->deleteFromDisk($attachment);
        });
    }

    public function scopePubliclyVisible(Builder $query): Builder
    {
        return $query->where('visibility', self::VISIBILITY_PUBLIC);
    }
}
