<?php

namespace App\Models\Contact\Hub;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Storage;

class ContactMessageAttachment extends Model
{
    protected $table = 'contact_message_attachments';

    protected $fillable = [
        'contact_message_id',
        'disk',
        'path',
        'filename',
        'mime',
        'size',
        'extraction_status',
        'extracted_text',
    ];

    public function message(): BelongsTo
    {
        return $this->belongsTo(ContactMessage::class, 'contact_message_id');
    }

    public function contents(): string
    {
        return Storage::disk($this->disk)->get($this->path);
    }

    public function base64Contents(): string
    {
        return base64_encode($this->contents());
    }

    public function signedUrl(?int $minutes = 30): ?string
    {
        $disk = Storage::disk($this->disk);
        if (method_exists($disk, 'temporaryUrl')) {
            try {
                return $disk->temporaryUrl($this->path, now()->addMinutes($minutes));
            } catch (\Throwable) {
                return null;
            }
        }
        return null;
    }
}
