<?php

namespace App\Models\Communication;

use App\Enum\Communication\CommunicationEventType;
use App\Models\Solicitor\Solicitor;
use App\Models\User\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class CommunicationEvent extends Model {
    protected $table = 'communication_events';

    protected $guarded = [];

    protected $casts = [
        'payload' => 'array',
        'occurred_at' => 'datetime',
        'event' => CommunicationEventType::class,
    ];

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

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

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

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

    public function scopeForSolicitor(Builder $query, int $solicitorId): Builder {
        return $query->where('solicitor_id', $solicitorId);
    }

    public function scopeForCommunication(Builder $query, int $communicationId): Builder {
        return $query->where('communication_id', $communicationId);
    }

    public function scopeForCall(Builder $query, int $callId): Builder {
        return $query->where('call_id', $callId);
    }

    public function scopeEvent(Builder $query, CommunicationEventType|string $event): Builder {
        return $query->where('event', $event instanceof CommunicationEventType ? $event->value : $event);
    }

    public function scopeSource(Builder $query, string $source): Builder {
        return $query->where('source', $source);
    }

    public function scopeLatestFirst(Builder $query): Builder {
        return $query->orderByDesc('occurred_at')->orderByDesc('id');
    }

    public function getEventLabelAttribute(): string {
        if ($this->event instanceof CommunicationEventType) {
            return str($this->event->value)->replace('_', ' ')->title()->toString();
        }

        return str((string)$this->event)->replace('_', ' ')->title()->toString();
    }
}