<?php

namespace App\Domains\Link\Models;

use App\Domains\Analytics\Models\Click;
use App\Domains\Domain\Models\Domain;
use App\Domains\Workspace\Models\Workspace;
use Database\Factories\LinkFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Link extends Model
{
    /** @use HasFactory<LinkFactory> */
    use HasFactory, SoftDeletes;

    protected $guarded = ['id'];

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

    protected static function booted(): void
    {
        static::creating(function (self $model) {
            if (empty($model->ulid)) {
                $model->ulid = Str::ulid();
            }
        });
    }

    protected $casts = [
        'rules' => 'array',
        'pixel_config' => 'array',
        'tags' => 'array',
        'expires_at' => 'datetime',
    ];

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

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

    /** @return HasMany<LinkVariant, $this> */
    public function variants(): HasMany
    {
        return $this->hasMany(LinkVariant::class);
    }

    /** @return HasMany<Click, $this> */
    public function clicks(): HasMany
    {
        return $this->hasMany(Click::class);
    }

    public function isActive(): bool
    {
        if ($this->status !== 'active') {
            return false;
        }
        if ($this->expires_at && $this->expires_at->isPast()) {
            return false;
        }

        return true;
    }
}
