<?php

namespace App\Domains\Ticket\Models;

use App\Domains\Auth\Models\User;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

#[Fillable([
    'tenant_code',
    'ticket',
    'name',
    'description',
    'source_catalog_item_id',
    'source_variant_id',
    'starts_at',
    'expires_at',
    'used_at',
    'user_id',
])]
class Ticket extends Model
{
    use HasFactory;

    public $timestamps = false;

    protected $appends = [
        'is_valid',
        'is_expired',
        'is_used',
    ];

    protected function casts(): array
    {
        return [
            'source_catalog_item_id' => 'integer',
            'source_variant_id' => 'integer',
            'starts_at' => 'datetime',
            'expires_at' => 'datetime',
            'used_at' => 'datetime',
            'user_id' => 'integer',
        ];
    }

    /** @return BelongsTo<Tenant, $this> */
    public function tenant(): BelongsTo
    {
        return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
    }

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

    public function isValid(): bool
    {
        $now = now();

        return $this->used_at === null
            && ($this->starts_at === null || $this->starts_at->lessThanOrEqualTo($now))
            && ($this->expires_at === null || $this->expires_at->greaterThan($now));
    }

    public function getIsValidAttribute(): bool
    {
        return $this->isValid();
    }

    public function getIsExpiredAttribute(): bool
    {
        return $this->used_at === null
            && $this->expires_at !== null
            && $this->expires_at->lessThanOrEqualTo(now());
    }

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