<?php

namespace App\Models\Monitoring;

use App\Models\Monitoring\Log;
use App\Models\Environments\Environment;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

class Report extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'reports';

    protected $fillable = [
        'environment_id',
        'model',
        'date',
        'value',
    ];

    protected $casts = [
        'value' => 'float',
        'date' => 'date',
    ];

    public function environment()
    {
        return $this->belongsTo(Environment::class);
    }

    /**
     * Last % difference
     */
    public static function last(int $environment_id, string $model, int $days): array
    {
        $deadline = now()->subDays($days);

        $reports = self::where('environment_id', $environment_id)
            ->where('model', $model)
            ->where('date', '>', $deadline)
            ->orderByDesc('date')
            ->get();

        if ($reports->isEmpty()) {
            return [
                'pctg' => 0,
                'desc' => '',
            ];
        }

        $current = $reports->first();
        $last = $reports->count() > 1 ? $reports->last() : $current;

        $currentval = (float) $current->value;
        $lastval = (float) $last->value;

        $pct = !empty($lastval) ? ($currentval - $lastval) / $lastval : 0;

        return [
            'pctg' => $pct * 100,
            'desc' => $current->date . " ({$currentval}) - {$last->date} ({$lastval})",
        ];
    }

    /**
     * Log/Upsert a report value
     */
    public static function log(int $environment_id, string $model, float $value)
    {
        $params = [
            'environment_id' => $environment_id,
            'model'   => $model,
            'date'    => now()->toDateString(),
        ];

        try {
            $existing = DB::table('reports')->where($params)->first();

            if ($existing) {
                DB::table('reports')->where('id', $existing->id)->update(['value' => $value]);
            } else {
                DB::table('reports')->insert(array_merge($params, ['value' => $value]));
            }

        } catch (\Exception $e) {
            Log::db('danger', '22000', 'Report Log', 'Environment', $environment_id, $e->getMessage());
        }
    }
}

