<?php

namespace DariusMure\Captcha\Models;

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

class CaptchaStatistic extends Model
{
    use HasFactory;

    protected $fillable = [
        'provider',
        'location',
        'ip_address',
        'user_agent',
        'success',
        'score',
        'error_code',
        'error_message',
        'response_time_ms',
        'metadata',
        'verified_at',
    ];

    protected $casts = [
        'success' => 'boolean',
        'score' => 'decimal:2',
        'response_time_ms' => 'integer',
        'metadata' => 'array',
        'verified_at' => 'datetime',
    ];

    /**
     * Get success rate for a provider
     */
    public static function getSuccessRate(string $provider, int $days = 7): float
    {
        $total = self::where('provider', $provider)
            ->where('created_at', '>=', now()->subDays($days))
            ->count();

        if ($total === 0) {
            return 0.0;
        }

        $successful = self::where('provider', $provider)
            ->where('created_at', '>=', now()->subDays($days))
            ->where('success', true)
            ->count();

        return round(($successful / $total) * 100, 2);
    }

    /**
     * Get average response time for a provider
     */
    public static function getAverageResponseTime(string $provider, int $days = 7): int
    {
        return (int) self::where('provider', $provider)
            ->where('created_at', '>=', now()->subDays($days))
            ->avg('response_time_ms');
    }

    /**
     * Get statistics grouped by location
     */
    public static function getLocationStats(int $days = 7): array
    {
        return self::where('created_at', '>=', now()->subDays($days))
            ->selectRaw('
                location,
                COUNT(*) as total,
                SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) as successful,
                SUM(CASE WHEN success = 0 THEN 1 ELSE 0 END) as failed
            ')
            ->groupBy('location')
            ->get()
            ->toArray();
    }

    /**
     * Clean old statistics
     */
    public static function cleanOldRecords(int $days = 90): int
    {
        return self::where('created_at', '<', now()->subDays($days))->delete();
    }
}
