﻿<?php

namespace App\Models;

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

class JobDescriptionExport extends Model
{
    use HasFactory;

    protected $fillable = [
        'job_description_id',
        'export_type',
        'exported_by',
        'file_path',
        'share_token',
        'expires_at',
    ];

    protected $casts = [
        'created_at' => 'datetime',
        'expires_at' => 'datetime',
    ];

    const TYPE_PDF  = 'pdf';
    const TYPE_DOCX = 'docx';
    const TYPE_LINK = 'link';

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

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

    public function getFileUrlAttribute(): ?string
    {
        if ($this->file_path && in_array($this->export_type, [self::TYPE_PDF, self::TYPE_DOCX])) {
            return asset('storage/' . $this->file_path);
        }

        return null;
    }

    public function getShareUrlAttribute(): ?string
    {
        if ($this->export_type === self::TYPE_LINK && $this->share_token) {
            return route('jd.shared', ['token' => $this->share_token]);
        }

        return null;
    }

    public function scopeOfType($query, string $type)
    {
        return $query->where('export_type', $type);
    }

    public function scopeNonExpired($query)
    {
        return $query->where(function ($q) {
            $q->whereNull('expires_at')->orWhere('expires_at', '>', now());
        });
    }

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

    public function deleteFile(): bool
    {
        if ($this->file_path && Storage::disk('public')->exists($this->file_path)) {
            return Storage::disk('public')->delete($this->file_path);
        }

        return false;
    