<?php
declare(strict_types=1);

namespace App\Controllers\Api;

use App\Middleware\ApiToken;
use App\Middleware\TenantScope;
use App\Models\Round;
use Core\Controller;
use Core\DB;

/**
 * Mobile-facing Rounds API.
 *   POST /api/v1/rounds/start/{templateId}          → { run_id }
 *   GET  /api/v1/rounds/run/{runId}                 → { run, stops[] }
 *   POST /api/v1/rounds/check-stop/{runStopId}      body { reading_value?, reading_text?, is_ok?, note? }
 *   POST /api/v1/rounds/complete/{runId}            body { notes? }
 *   POST /api/v1/rounds/abandon/{runId}
 *   GET  /api/v1/rounds/index                       → active + recent runs for the operator
 */
final class RoundsController extends Controller
{
    public function middleware(): array
    {
        return [ApiToken::class, TenantScope::class];
    }

    private function tenantId(): int { return (int) ($_SESSION['tenant_id'] ?? 0); }
    private function userId():   int { return (int) ($_SESSION['user']['user_id'] ?? 0); }

    public function index(): void
    {
        $tenantId = $this->tenantId();
        $this->json([
            'data' => [
                'templates' => Round::templatesForTenant($tenantId),
                'recent'    => Round::recentRuns($tenantId, 10),
            ],
        ]);
    }

    public function start(int $templateId): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') $this->json(['error' => 'POST required'], 405);
        if (!Round::findTemplate($this->tenantId(), $templateId)) $this->json(['error' => 'Template not found'], 404);
        $runId = Round::startRun($this->tenantId(), $templateId, $this->userId() ?: 0);
        $this->json([
            'success' => true,
            'run_id'  => $runId,
            'run'     => Round::findRun($this->tenantId(), $runId),
            'stops'   => Round::runStopsFor($runId),
        ]);
    }

    public function run(int $runId): void
    {
        $run = Round::findRun($this->tenantId(), $runId);
        if (!$run) $this->json(['error' => 'Not found'], 404);
        $this->json([
            'data' => [
                'run'   => $run,
                'stops' => Round::runStopsFor($runId),
            ],
        ]);
    }

    public function checkStop(int $runStopId): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') $this->json(['error' => 'POST required'], 405);
        // Guard the tenant scope by joining back to round_runs.
        $ownerCheck = DB::one(
            'SELECT rrs.run_stop_id
               FROM round_run_stops rrs
               JOIN round_runs rr ON rr.run_id = rrs.run_id
              WHERE rrs.run_stop_id = :id AND rr.tenant_id = :t',
            ['id' => $runStopId, 't' => $this->tenantId()]
        );
        if (!$ownerCheck) $this->json(['error' => 'Not found'], 404);
        Round::checkOffStop($runStopId, $this->input());
        $this->json(['success' => true]);
    }

    public function complete(int $runId): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') $this->json(['error' => 'POST required'], 405);
        if (!Round::findRun($this->tenantId(), $runId)) $this->json(['error' => 'Not found'], 404);
        $body = $this->input();
        Round::completeRun($this->tenantId(), $runId, $body['notes'] ?? null);
        $this->json(['success' => true]);
    }

    public function abandon(int $runId): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') $this->json(['error' => 'POST required'], 405);
        if (!Round::findRun($this->tenantId(), $runId)) $this->json(['error' => 'Not found'], 404);
        Round::abandonRun($this->tenantId(), $runId);
        $this->json(['success' => true]);
    }
}
