<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Cache;
use Morilog\Jalali\Jalalian;

class Score extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'user_id',

        'score',
        'description',
        'type',
    ];

    protected $casts = [
        'user_id' => 'integer',
        'score' => 'integer',
    ];

    /**
     * additional data
     */
    protected $appends = [
        'get_formatted_score',
        'jalali_created_at',
        'jalali_updated_at',
    ];

    public function getGetFormattedScoreAttribute()
    {
        return number_format($this->score);
    }

    public function getJalaliCreatedAtAttribute()
    {
        $date = [
            Jalalian::forge($this->created_at)->format('%d %B %Y'),
            Jalalian::forge($this->created_at)->format('Y/m/d'),
            Jalalian::forge($this->created_at)->format('H:i - Y/m/d'),
            Jalalian::forge($this->created_at)->ago(),
            Jalalian::forge($this->created_at)->getTimestamp(),
        ];
        return $date;
    }

    public function getJalaliUpdatedAtAttribute()
    {
        $date = [
            Jalalian::forge($this->updated_at)->format('%d %B %Y'),
            Jalalian::forge($this->updated_at)->format('Y/m/d'),
            Jalalian::forge($this->updated_at)->format('H:i - Y/m/d'),
            Jalalian::forge($this->updated_at)->ago(),
            Jalalian::forge($this->updated_at)->getTimestamp(),
        ];
        return $date;
    }
    /** end append */

    /**
     * remove cache data in update
     */
    protected static function boot()
    {
        parent::boot();

        static::saved(function ($score) {
            Cache::forget('score_increase_' . $score->user_id);
            Cache::forget('score_decrease_' . $score->user_id);
        });

        static::deleted(function ($score) {
            Cache::forget('score_increase_' . $score->user_id);
            Cache::forget('score_decrease_' . $score->user_id);
        });
    }

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