<?php

namespace App\Models;

use App\Traits\BelongsToOrg;
use Database\Factories\CompletionReportFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

class CompletionReport extends Model implements HasMedia
{
    /** @use HasFactory<CompletionReportFactory> */
    use BelongsToOrg, HasFactory, InteractsWithMedia, SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'project_charter_deliverable_id',
        'name',
        'description',
        'cost',
        'delivery_date',
        'created_by',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'delivery_date' => 'date',
            'cost' => 'decimal:2',
        ];
    }

    /**
     * Get the project charter deliverable that this completion report belongs to.
     */
    public function projectCharterDeliverable(): BelongsTo
    {
        return $this->belongsTo(ProjectCharterDeliverable::class);
    }

    /**
     * Get the user who created this completion report.
     */
    public function createdBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Get the exchange request for this completion report.
     */
    public function exchangeRequest(): HasOne
    {
        return $this->hasOne(ExchangeRequest::class);
    }

    /**
     * Check if completion report has a file
     */
    public function hasFile(): bool
    {
        return $this->getFirstMedia('report_file') !== null;
    }

    /**
     * Register media collections.
     */
    public function registerMediaCollections(): void
    {
        $this->addMediaCollection('report_file')
            ->singleFile()
            ->acceptsMimeTypes(['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'image/jpeg', 'image/png']);
    }

    /**
     * Register media conversions.
     */
    public function registerMediaConversions(?Media $media = null): void
    {
        $this->addMediaConversion('thumb')
            ->width(300)
            ->height(300)
            ->sharpen(10);
    }

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (Auth::check() && ! $model->created_by) {
                $model->created_by = Auth::id();
            }
        });
    }
}
