<?php

namespace App\Models\Contact\Hub;

use App\Models\Dsar\DsarEvidenceItem;
use App\Trait\HasEvidenceProductivity;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Storage;

class ContactMessageAttachment extends Model
{
    use HasEvidenceProductivity;

    protected $table = 'contact_message_attachments';

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

    protected $casts = [
        'evidence_is_dsar_doc' => 'boolean',
        'evidence_excluded'    => 'boolean',
    ];

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

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

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

        if ($contents === null) {
            throw new \RuntimeException("Attachment file not found: {$this->path}");
        }

        return $contents;
    }

    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;
    }
}
