<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Mtc\MercuryDataModels\Factories\ContentSyncFactory;
use Mtc\MercuryDataModels\Tenant;
use Mtc\MercuryDataModels\User;

class ContentSync extends Model
{
    use HasFactory;

    public const PROVIDE = 'provide';
    public const RECEIVE = 'receive';
    public const PUSH = 'push';
    public const PULL = 'pull';
    public const TTL = 90;

    protected $fillable = [
        'tenant_id',
        'user_id',
        'token',
        'details',
        'data',
        'finished',
        'failed',
        'errors'
    ];

    protected $casts = [
        'finished' => 'boolean',
        'failed' => 'boolean',
        'details' => 'array',
        'data' => 'array',
        'errors' => 'array',
        'created_at' => 'datetime:d/m/Y H:i',
    ];

    protected $appends = [
        'status'
    ];


    protected static function newFactory()
    {
        return ContentSyncFactory::new();
    }

    public function tenant(): BelongsTo
    {
        return $this->belongsTo(Tenant::class);
    }

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

    public function getStatusAttribute()
    {
        if (Carbon::now()->subMinutes(self::TTL)->gt($this->created_at)) {
            return 'Expired';
        }

        return 'Active';
    }
}
