<?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;
use Stancl\Tenancy\Database\Concerns\CentralConnection;

class ContentSync extends Model
{
    use HasFactory;
    use CentralConnection;

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

    public const APPROVAL_PENDING = 'pending';
    public const APPROVAL_APPROVED = 'approved';
    public const APPROVAL_REJECTED = 'rejected';

    protected $fillable = [
        'tenant_id',
        'user_id',
        'token',
        'details',
        'data',
        'finished',
        'failed',
        'errors',
        'approval_status',
        'approval_reason',
        'approved_by',
        'approved_at',
        'approval_notes',
    ];

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

    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 approvedByUser(): BelongsTo
    {
        return $this->belongsTo(User::class, 'approved_by');
    }

    public function isPendingApproval(): bool
    {
        return $this->approval_status === self::APPROVAL_PENDING;
    }

    public function isApproved(): bool
    {
        return $this->approval_status === self::APPROVAL_APPROVED;
    }

    public function isRejected(): bool
    {
        return $this->approval_status === self::APPROVAL_REJECTED;
    }

    public function requiresApproval(): bool
    {
        return $this->approval_status !== null;
    }

    public function getStatusAttribute()
    {
        if ($this->approval_status === self::APPROVAL_PENDING) {
            return 'Pending Approval';
        }

        if ($this->approval_status === self::APPROVAL_REJECTED) {
            return 'Rejected';
        }

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

        return 'Active';
    }
}
