<?php

namespace Licenzo\Model;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

use Licenzo\Framework\Database\Model;

class IdempotencyKey extends Model
{
    protected $table = 'licenzo_idempotency_keys';

    const STATUS_PROCESSING = 'processing';
    const STATUS_PROCESSED = 'processed';
    const STATUS_FAILED = 'failed';
    const STATUS_EXPIRED = 'expired';

    protected $fillable = [
        'provider',
        'event_scope',
        'event_key',
        'key_hash',
        'subscription_id',
        'customer_id',
        'status',
        'payload_checksum',
        'processed_at',
        'expires_at'
    ];

    protected $casts = [
        'id' => 'int',
        'subscription_id' => 'int',
        'customer_id' => 'int',
        'processed_at' => 'datetime',
        'expires_at' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    public function subscription()
    {
        return $this->belongsTo(Subscription::class);
    }

    public function customer()
    {
        return $this->belongsTo(Customer::class);
    }

    public function scopeByProvider($query, string $provider)
    {
        return $query->where('provider', $provider);
    }

    public function scopeByScope($query, string $scope)
    {
        return $query->where('event_scope', $scope);
    }

    public function scopeProcessing($query)
    {
        return $query->where('status', static::STATUS_PROCESSING);
    }

    public function scopeProcessed($query)
    {
        return $query->where('status', static::STATUS_PROCESSED);
    }

    public function markAsProcessed(): bool
    {
        return $this->update([
            'status' => static::STATUS_PROCESSED,
            'processed_at' => gmdate('Y-m-d H:i:s')
        ]);
    }

    public function markAsFailed(): bool
    {
        return $this->update([
            'status' => static::STATUS_FAILED
        ]);
    }

    public static function hash(string $provider, string $eventScope, string $eventKey): string
    {
        return hash('sha256', $provider . ':' . $eventScope . ':' . $eventKey);
    }
}
