<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;

class CaseItem extends Model
{
    use HasFactory, LogsActivity;

    protected $table = 'cases';

    protected $fillable = [
        'client_id',
        'created_by',
        'label',
        'source',
        'sentiment',
        'post_date',
        'post_time',
        'post_text',
        'translation',
        'post_link',
        'action_social',
        'notes_social',
        'user_reply',
        'status',
        'last_status_changed_at',
        'closed_at',
        'last_notified_at',
        'escalation_state',
    ];

    protected function casts(): array
    {
        return [
            'post_date' => 'date',
            'post_time' => 'string',
            'last_status_changed_at' => 'datetime',
            'closed_at' => 'datetime',
            'last_notified_at' => 'datetime',
        ];
    }

    public function client()
    {
        return $this->belongsTo(Client::class);
    }

    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function owners()
    {
        return $this->belongsToMany(User::class, 'case_user_assignments', 'case_id', 'user_id')
            ->withTimestamps();
    }

    public function comments()
    {
        return $this->hasMany(CaseComment::class, 'case_id');
    }

    public function customFieldValues()
    {
        return $this->hasMany(CaseCustomFieldValue::class, 'case_id');
    }

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logFillable()
            ->useLogName('case')
            ->logOnlyDirty();
    }
}
