<?php

namespace App\Domain\Documents\Models;

use App\Domain\Documents\Enums\DocumentStatus;
use App\Domain\Identity\Models\User;
use App\Domain\Organization\Models\Company;
use App\Support\Concerns\HasUuid;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class Document extends Model
{
    use HasFactory, HasUuid, SoftDeletes;

    protected $guarded = ['id', 'uuid'];

    protected $hidden = ['file_path'];

    protected function casts(): array
    {
        return [
            'verification_status' => DocumentStatus::class,
            'issue_date' => 'date',
            'expiry_date' => 'date',
            'verified_at' => 'datetime',
            'is_current' => 'boolean',
            'version' => 'integer',
            'size_bytes' => 'integer',
        ];
    }

    public function company(): BelongsTo
    {
        return $this->belongsTo(Company::class);
    }

    public function documentType(): BelongsTo
    {
        return $this->belongsTo(DocumentType::class);
    }

    public function owner(): MorphTo
    {
        return $this->morphTo();
    }

    public function uploadedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'uploaded_by');
    }

    public function verifiedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'verified_by');
    }

    public function replaces(): BelongsTo
    {
        return $this->belongsTo(self::class, 'replaces_document_id');
    }

    public function accessLogs(): HasMany
    {
        return $this->hasMany(DocumentAccessLog::class)->latest('accessed_at');
    }

    public function scopeCurrent(Builder $query): Builder
    {
        return $query->where('is_current', true);
    }

    public function scopeAwaitingReview(Builder $query): Builder
    {
        return $query->whereIn('verification_status', [
            DocumentStatus::Uploaded->value,
            DocumentStatus::UnderReview->value,
        ]);
    }

    public function hasExpired(): bool
    {
        return $this->expiry_date !== null && $this->expiry_date->isPast();
    }

    public function expiresWithin(int $days): bool
    {
        return $this->expiry_date !== null
            && ! $this->hasExpired()
            && $this->expiry_date->isBefore(now()->addDays($days));
    }

    /**
     * An expired document is treated as unusable regardless of its stored
     * status: verification does not outlive the paper.
     */
    public function effectiveStatus(): DocumentStatus
    {
        if ($this->hasExpired() && $this->verification_status === DocumentStatus::Verified) {
            return DocumentStatus::Expired;
        }

        return $this->verification_status;
    }

    public function isSatisfied(): bool
    {
        return $this->effectiveStatus()->isSatisfied();
    }

    /** Full version chain, oldest first. */
    public function versionChain(): \Illuminate\Support\Collection
    {
        return self::withTrashed()
            ->where('owner_type', $this->owner_type)
            ->where('owner_id', $this->owner_id)
            ->where('document_type_id', $this->document_type_id)
            ->orderBy('version')
            ->get();
    }
}
