<?php

namespace Modules\Feedback\Entities;

use App\Traits\HasDocuments;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;
use Modules\Auth\Entities\User;

class Feedback extends Model
{
    use HasDocuments, HasUuids, SoftDeletes, LogsActivity;

    public const IMAGE_DOCUMENT_TYPE = 'image';

    public const VIDEO_DOCUMENT_TYPE = 'video';

    protected $table = 'feedback';

    protected $fillable = [
        'user_id',
        'type',
        'title',
        'description',
        'page_url',
        'browser_info',
        'steps_to_reproduce',
        'expected_behavior',
        'actual_behavior',
        'additional_notes',
        'priority',
        'status',
        'assigned_to',
        'admin_notes',
        'resolved_at',
    ];

    protected $casts = [
        'browser_info' => 'array',
        'resolved_at' => 'datetime',
    ];

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logAll()
            ->logOnlyDirty();
    }

    /**
     * Get the user who submitted the feedback
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * Get the admin assigned to handle this feedback
     */
    public function assignedUser()
    {
        return $this->belongsTo(User::class, 'assigned_to');
    }

    public function images(): MorphMany
    {
        return $this->documents()->where('type', self::IMAGE_DOCUMENT_TYPE);
    }

    public function videos(): MorphMany
    {
        return $this->documents()->where('type', self::VIDEO_DOCUMENT_TYPE);
    }

    /**
     * Scope for filtering by type
     */
    public function scopeOfType($query, $type)
    {
        return $query->where('type', $type);
    }

    /**
     * Scope for filtering by status
     */
    public function scopeOfStatus($query, $status)
    {
        return $query->where('status', $status);
    }

    /**
     * Scope for filtering by priority
     */
    public function scopeOfPriority($query, $priority)
    {
        return $query->where('priority', $priority);
    }

    /**
     * Scope for open feedback
     */
    public function scopeOpen($query)
    {
        return $query->whereIn('status', ['open', 'in_progress']);
    }

    /**
     * Scope for resolved feedback
     */
    public function scopeResolved($query)
    {
        return $query->whereIn('status', ['resolved', 'closed']);
    }
}
