<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class LocalizationCache extends Model
{
    use HasFactory;

    protected $table = 'localization_cache';

    protected $fillable = [
        'source_text_hash',
        'source_locale',
        'target_locale',
        'tone',
        'source_text',
        'translated_text',
        'cultural_notes',
        'ai_provider',
        'usage_count',
        'last_used_at',
    ];

    protected $casts = [
        'last_used_at' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'usage_count' => 'integer',
    ];

    /**
     * Generate hash for source text.
     */
    public static function generateHash(string $sourceText, string $sourceLocale, string $targetLocale, string $tone): string
    {
        return hash('sha256', $sourceText . '|' . $sourceLocale . '|' . $targetLocale . '|' . $tone);
    }

    /**
     * Find cached translation.
     */
    public static function findCached(string $sourceText, string $sourceLocale, string $targetLocale, string $tone): ?self
    {
        $hash = self::generateHash($sourceText, $sourceLocale, $targetLocale, $tone);
        
        return self::where('source_text_hash', $hash)
            ->where('source_locale', $sourceLocale)
            ->where('target_locale', $targetLocale)
            ->where('tone', $tone)
            ->first();
    }

    /**
     * Increment usage count and update last used timestamp.
     */
    public function incrementUsage(): void
    {
        $this->increment('usage_count');
        $this->update(['last_used_at' => now()]);
    }

    /**
     * Scope to filter by target locale.
     */
    public function scopeForTargetLocale($query, string $locale)
    {
        return $query->where('target_locale', $locale);
    }

    /**
     * Scope to filter by tone.
     */
    public function scopeWithTone($query, string $tone)
    {
        return $query->where('tone', $tone);
    }

    /**
     * Scope to get most used translations.
     */
    public function scopeMostUsed($query, int $limit = 10)
    {
        return $query->orderBy('usage_count', 'desc')->limit($limit);
    }

    /**
     * Scope to get recently used translations.
     */
    public function scopeRecentlyUsed($query, int $limit = 10)
    {
        return $query->orderBy('last_used_at', 'desc')->limit($limit);
    }
}