<?php

namespace App\Models;

use Illuminate\Support\Facades\Date;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Log extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id',
        'ip',
        'email',
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public static function deleteLogsFromDB(): string
    {
        $cutoff = Date::now('UTC')->subMonths(3)->toDateTimeString();
        $count = count(self::query()->where('created_at', '<', $cutoff)->latest()
            ->get());

        if ($count > 0) {
            self::query()->where('created_at', '<', $cutoff)->delete();

            return "$count old log(s) deleted from the database.";
        }

        return 'No logs older than 3 months found.';
    }
}
