<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Storage;

class BulkImportLog extends Model
{
    protected $table = 'bulk_import_log';

    protected $fillable = [
        'object_type',
        'import_type',
        'user_id',
        'data',
        'automations',
        'filename',
    ];

    protected $casts = [
        'data' => 'array',
        'automations' => 'array',
        'created_at' => 'datetime',
    ];

    #[\Override]
    protected static function boot()
    {
        parent::boot();

        self::created(fn(self $entry) => $entry->clearOldEntries());
    }

    public function author(): BelongsTo
    {
        return $this->belongsTo(\Mtc\MercuryDataModels\User::class, 'user_id');
    }

    private function clearOldEntries()
    {
        self::query()
            ->where('object_type', $this->object_type)
            ->latest()
            ->take(5)
            ->skip(5)
            ->get()
            ->each(fn(self $log) => Storage::disk('file-storage')->delete($log->filename))
            ->each(fn(self $log) => $log->delete());
    }
}
