<?php

namespace Modules\SystemCore\App\Models;

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

class SupplierDocument extends Model
{
    use SoftDeletes;

    protected $table = 'supplier_documents';

    protected $fillable = [
        'supplier_id',
        'document_title',
        'document_number',
        'document_type',
        'file_path',
        'file_name',
        'mime_type',
        'file_size',
        'issue_date',
        'expiry_date',
        'notes',
        'is_active',
    ];

    protected function casts(): array
    {
        return [
            'issue_date' => 'date',
            'expiry_date' => 'date',
            'is_active' => 'boolean',
            'file_size' => 'integer',
        ];
    }

    /**
     * Get the supplier that owns the document.
     */
    public function supplier(): BelongsTo
    {
        return $this->belongsTo(CoreSupplier::class, 'supplier_id');
    }

    /**
     * Check if the document is expired.
     */
    public function isExpired(): bool
    {
        return $this->expiry_date && $this->expiry_date->isPast();
    }

    /**
     * Check if the document is about to expire.
     */
    public function isAboutToExpire(int $days = 30): bool
    {
        return $this->expiry_date &&
               ! $this->expiry_date->isPast() &&
               $this->expiry_date->diffInDays(now()) <= $days;
    }

    /**
     * Get the file URL attribute.
     */
    public function getFileUrlAttribute(): ?string
    {
        if (! $this->file_path) {
            return null;
        }

        return Storage::disk('public')->url($this->file_path);
    }

    /**
     * Scope a query to only include documents that are expired.
     */
    public function scopeExpired($query)
    {
        return $query->whereNotNull('expiry_date')
            ->whereDate('expiry_date', '<', now());
    }

    /**
     * Scope a query to only include documents that are about to expire.
     */
    public function scopeAboutToExpire($query, int $days = 30)
    {
        $futureDate = now()->addDays($days);

        return $query->whereNotNull('expiry_date')
            ->whereDate('expiry_date', '>', now())
            ->whereDate('expiry_date', '<=', $futureDate);
    }

    /**
     * Scope a query to only include active documents.
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope a query to filter by document type.
     */
    public function scopeByType($query, string $type)
    {
        return $query->where('document_type', $type);
    }

    /**
     * Get formatted file size.
     */
    public function getFormattedFileSizeAttribute(): string
    {
        if (! $this->file_size) {
            return 'N/A';
        }

        $units = ['B', 'KB', 'MB', 'GB'];
        $size = $this->file_size;
        $unitIndex = 0;

        while ($size >= 1024 && $unitIndex < count($units) - 1) {
            $size /= 1024;
            $unitIndex++;
        }

        return round($size, 2).' '.$units[$unitIndex];
    }
}
