<?php

namespace App\Models;

use App\Enums\ActivityTypeEnum;
use Database\Factories\ActivityLogFactory;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Carbon;

/**
 * @property int $id
 * @property ActivityTypeEnum $type
 * @property string $message
 * @property array<string, mixed>|null $context
 * @property string|null $subject_type
 * @property int|null $subject_id
 * @property Carbon $logged_at
 * @property Carbon $created_at
 * @property Carbon $updated_at
 */
class ActivityLog extends Model
{
    /** @use HasFactory<ActivityLogFactory> */
    use HasFactory;

    protected $fillable = [
        'type',
        'message',
        'context',
        'subject_type',
        'subject_id',
        'logged_at',
    ];

    protected $casts = [
        'type' => ActivityTypeEnum::class,
        'context' => 'array',
        'logged_at' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    /**
     * @return MorphTo<Model, $this>
     */
    public function subject(): MorphTo
    {
        return $this->morphTo();
    }

    /**
     * @param  Builder<ActivityLog>  $query
     * @return Builder<ActivityLog>
     */
    public function scopeOfType(Builder $query, ActivityTypeEnum $type): Builder
    {
        return $query->where('type', $type);
    }

    /**
     * @param  Builder<ActivityLog>  $query
     * @return Builder<ActivityLog>
     */
    public function scopeSince(Builder $query, Carbon $since): Builder
    {
        return $query->where('logged_at', '>=', $since);
    }

    /**
     * @param  Builder<ActivityLog>  $query
     * @return Builder<ActivityLog>
     */
    public function scopeLatestFirst(Builder $query): Builder
    {
        return $query->orderByDesc('logged_at')->orderByDesc('id');
    }

    /**
     * @param  Builder<ActivityLog>  $query
     * @return Builder<ActivityLog>
     */
    public function scopeWithSubjectDetails(Builder $query): Builder
    {
        return $query->with(['subject' => function (Relation $morphTo): void {
            if ($morphTo instanceof MorphTo) {
                $morphTo->morphWith([Article::class => ['feed']]);
            }
        }]);
    }
}
