<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;

/**
 * Hour-aligned (or day-aligned) uptime aggregates. One row per
 * (target, location, bucket_start, size). location_id=null = consensus
 * (aggregated across all locations).
 *
 * The consensus bucket is what gets shown to the user as "the" uptime
 * percentage for a server/site over a given period.
 */
class UptimeBucket extends Model
{
    use HasFactory;

    protected $fillable = [
        'target_type', 'target_id', 'probe_location_id',
        'bucket_starts_at', 'bucket_size',
        'checks_total', 'checks_up', 'uptime_pct', 'avg_response_ms',
    ];

    protected function casts(): array
    {
        return [
            'bucket_starts_at' => 'datetime',
            'uptime_pct' => 'decimal:2',
        ];
    }

    public function target(): MorphTo
    {
        return $this->morphTo();
    }

    public function location(): BelongsTo
    {
        return $this->belongsTo(ProbeLocation::class, 'probe_location_id');
    }
}
