<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Shortlink extends Model
{
    protected $fillable = [
        'user_id',
        'original_url',
        'short_code',
        'custom_alias',
        'title',
        'description',
        'og_image',
        'type',
        'is_active',
        'expires_at',
        'total_clicks',
        'unique_clicks',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'expires_at' => 'datetime',
        'total_clicks' => 'integer',
        'unique_clicks' => 'integer',
    ];

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

    public function clicks()
    {
        return $this->hasMany(Click::class);
    }

    // Helper Methods
    public function getShortUrl()
    {
        $code = $this->custom_alias ?: $this->short_code;
        return url($code);
    }

    public function incrementClicks($isUnique = false)
    {
        $this->increment('total_clicks');
        if ($isUnique) {
            $this->increment('unique_clicks');
        }
    }

    public function isExpired()
    {
        return $this->expires_at && $this->expires_at->isPast();
    }
}
