<?php

namespace App\Domains\Attachable\Models;

use App\Domains\Attachable\Enums\AttachmentType;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

#[Fillable([
    'key',
    'path',
    'filename',
    'type',
    'mime_type',
    'extension',
    'size',
])]
class Attachment extends Model
{
    use HasFactory;

    protected $table = 'attachments';

    protected static function booted(): void
    {
        static::creating(function (self $attachment): void {
            if (! $attachment->key) {
                $attachment->key = (string) Str::uuid();
            }
        });
    }

    protected function casts(): array
    {
        return [
            'type' => AttachmentType::class,
            'size' => 'integer',
        ];
    }

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

    public function desktopCrop(): HasOne
    {
        return $this->hasOne(AttachmentCrop::class)
            ->where('variant', AttachmentCrop::DESKTOP);
    }

    public function mobileCrop(): HasOne
    {
        return $this->hasOne(AttachmentCrop::class)
            ->where('variant', AttachmentCrop::MOBILE);
    }

    public function cropSource(): HasOne
    {
        return $this->hasOne(AttachmentCrop::class, 'cropped_attachment_id');
    }

    /**
     * Get the pre-signed temporary S3 URL for this attachment.
     */
    public function getTemporaryUrl(int $expiresInMinutes = 10): string
    {
        return Storage::disk('s3')->temporaryUrl(
            $this->path,
            now()->addMinutes($expiresInMinutes)
        );
    }
}
