<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Carbon\Carbon;

class ShortLink extends Model
{
    use HasFactory;
    
    protected $fillable = [
        'original_url',
        'short_code',
        'tenant_id',
        'usage_type',
        'expires_at',
        'click_count',
        'metadata',
        'created_by'
    ];
    
    protected $casts = [
        'expires_at' => 'datetime',
        'metadata' => 'json',
        'click_count' => 'integer'
    ];
    
    /**
     * Generate a unique short code
     */
    public static function generateUniqueCode(int $length = 6): string
    {
        do {
            $code = Str::random($length);
        } while (self::where('short_code', $code)->exists());
        
        return $code;
    }
    
    /**
     * Create a short link for display pairing
     */
    public static function createForDisplay(string $originalUrl, int $tenantId, int $displayId, ?string $createdBy = null): self
    {
        return self::create([
            'original_url' => $originalUrl,
            'short_code' => self::generateUniqueCode(),
            'tenant_id' => $tenantId,
            'usage_type' => 'display_pairing',
            'expires_at' => now()->addMonths(6), // Expire after 6 months
            'metadata' => [
                'display_id' => $displayId,
                'created_for' => 'display_pairing'
            ],
            'created_by' => $createdBy
        ]);
    }
    
    /**
     * Check if the short link is expired
     */
    public function isExpired(): bool
    {
        return $this->expires_at && $this->expires_at->isPast();
    }
    
    /**
     * Increment click count
     */
    public function recordClick(): void
    {
        $this->increment('click_count');
    }
    
    /**
     * Get the short URL
     */
    public function getShortUrlAttribute(): string
    {
        return url('/s/' . $this->short_code);
    }
    
    /**
     * Relationship with tenant
     */
    public function tenant()
    {
        return $this->belongsTo(Tenant::class);
    }
    
    /**
     * Scope for active (non-expired) links
     */
    public function scopeActive($query)
    {
        return $query->where(function($q) {
            $q->whereNull('expires_at')
              ->orWhere('expires_at', '>', now());
        });
    }
    
    /**
     * Scope for display pairing links
     */
    public function scopeDisplayPairing($query)
    {
        return $query->where('usage_type', 'display_pairing');
    }
}
