<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Cache;
use App\Traits\{ScopeActive,UsePostgres};

class Echoarea extends Model
{
	use SoftDeletes,ScopeActive,UsePostgres;

	private const CACHE_TIME = 3600;

	/* RELATIONS */

	public function addresses()
	{
		return $this->belongsToMany(Address::class);
	}

	public function domain()
	{
		return $this->belongsTo(Domain::class);
	}

	public function echomail()
	{
		return Echomail::select('*')
			->where('echoarea_id',$this->id);
	}

	/* ATTRIBUTES */

	public function getLastMessageAttribute(): ?Carbon
	{
		$key = sprintf('%s_%d','echo_last_message',$this->id);

		return Cache::driver('redis')->remember($key,self::CACHE_TIME,function() {
			return ($x=$this->echomail()->orderBy('datetime','DESC')->first()) ? $x->datetime : NULL;
		});
	}

	/* METHODS */

	public function messages_count(int $period): int
	{
		$key = sprintf('%s_%d_%d','echo_mesages_count',$this->id,$period);

		return Cache::driver('redis')->remember($key,self::CACHE_TIME,function() use ($period) {
			switch ($period) {
				case 1: // day
					return $this->echomail()->where('datetime','>=',Carbon::now()->startOfday()->subDay())->count();
				case 7: // week
					return $this->echomail()->where('datetime','>=',Carbon::now()->startOfday()->subWeek())->count();
				case 30: // month
					return $this->echomail()->where('datetime','>=',Carbon::now()->startOfday()->subMonth())->count();
				default:
					return 0;
			}
		});
	}
}