<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Server;
use App\Models\Website;
use App\Services\UptimeService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * Surfaces uptime percentages to the frontend. Two routes:
 *
 *   GET /uptime/{type}/{id}                Get uptime data for one target
 *      ?period=7d|30d|180d|365d  default returns all canonical periods
 *      ?location_id=N            optional, defaults to consensus
 *      ?breakdown=1              also include per-location breakdown
 */
class UptimeController extends Controller
{
    public function __construct(protected UptimeService $uptime) {}

    public function show(Request $request, string $type, int $id): JsonResponse
    {
        $target = $this->resolveTarget($type, $id);
        abort_unless($target, 404);

        $locationId = $request->integer('location_id') ?: null;
        $period = $request->string('period')->toString();
        $wantBreakdown = $request->boolean('breakdown');

        if ($period) {
            $data = ['summary' => $this->uptime->forPeriod($target, $period, $locationId)];
        } else {
            $data = ['periods' => $this->uptime->allPeriods($target, $locationId)];
        }

        if ($wantBreakdown) {
            $data['by_location'] = $this->uptime->byLocation(
                $target,
                $period ?: '30d'
            );
        }

        $data['target'] = [
            'type' => $type,
            'id' => $id,
            'consensus_status' => $target->consensus_status ?? 'unknown',
            'locations_total' => $target->locations_total ?? 0,
            'locations_reporting_down' => $target->locations_reporting_down ?? 0,
        ];

        return response()->json($data);
    }

    protected function resolveTarget(string $type, int $id)
    {
        return match ($type) {
            'server' => Server::find($id),
            'website' => Website::find($id),
            default => null,
        };
    }
}
