<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;

/**
 * @property int $id
 * @property string $original_name
 * @property string $file_name
 * @property string $file_path
 * @property string $mime_type
 * @property int $file_size
 * @property string $uploadable_type
 * @property int $uploadable_id
 * @property string $upload_source
 * @property string|null $uploaded_by
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @property-read mixed $formatted_size
 * @property-read mixed $url
 * @property-read Model|\Eloquent $uploadable
 *
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Attachment newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Attachment newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Attachment query()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Attachment whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Attachment whereFileName($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Attachment whereFilePath($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Attachment whereFileSize($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Attachment whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Attachment whereMimeType($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Attachment whereOriginalName($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Attachment whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Attachment whereUploadSource($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Attachment whereUploadableId($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Attachment whereUploadableType($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Attachment whereUploadedBy($value)
 *
 * @mixin \Eloquent
 */
class Attachment extends Model
{
    use HasFactory;

    protected $fillable = [
        'original_name',
        'file_name',
        'file_path',
        'mime_type',
        'file_size',
        'uploadable_type',
        'uploadable_id',
        'upload_source',
        'uploaded_by',
        // PRC-360 — antivirus scan lifecycle.
        'scan_status',
        'scan_message',
    ];

    /**
     * PRC-360 — true when the file passed the virus scan and is safe to
     * serve. NOT named isClean(): that collides with Eloquent's native
     * Model::isClean() (dirty-attribute tracking) — incompatible signature.
     */
    public function scanPassed(): bool
    {
        // null = legacy/pre-scan rows (already statically validated).
        return $this->scan_status === null || $this->scan_status === 'clean';
    }

    /** PRC-360 — true when the file was flagged infected (quarantined). */
    public function isQuarantined(): bool
    {
        return $this->scan_status === 'infected';
    }

    /** PRC-361 — public-disk relative path of the cached thumbnail (if any). */
    public function thumbnailPath(): string
    {
        return 'thumbnails/'.$this->id.'.jpg';
    }

    /** PRC-361 — true when a generated thumbnail already exists on disk. */
    public function hasThumbnail(): bool
    {
        return Storage::disk('public')->exists($this->thumbnailPath());
    }

    /**
     * Polymorphic ilişki - herhangi bir model'e bağlanabilir
     */
    public function uploadable()
    {
        return $this->morphTo();
    }

    /**
     * Dosya boyutunu okunabilir formatta döndürür
     */
    public function getFormattedSizeAttribute()
    {
        $bytes = $this->file_size;
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];

        for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
            $bytes /= 1024;
        }

        return round($bytes, 2).' '.$units[$i];
    }

    /**
     * Dosyanın var olup olmadığını kontrol eder
     */
    public function fileExists()
    {
        return Storage::disk('attachments')->exists($this->file_path)
            || Storage::disk('public')->exists($this->file_path);
    }

    /**
     * Güvenli dosya indirme URL'i oluşturur
     */
    public function getSecureDownloadUrl($ticketId = null)
    {
        if ($ticketId) {
            return route('store.auth.tickets.attachment.download', [$ticketId, $this->id]);
        }

        return null;
    }

    /**
     * Admin panel için güvenli indirme URL'ini döndürür
     */
    public function getUrlAttribute()
    {
        return route('admin.file-download', $this->id);
    }
}
