<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;

/**
 * Public installer status probe — surveyed by welcome page / health monitor.
 *
 * @OA\Tag(name="Install", description="Installer state probe")
 */
final class InstallStatusController extends Controller
{
    /**
     * @OA\Get(
     *   path="/api/v1/install/status",
     *   tags={"Install"},
     *   summary="Returns whether the installer has been finalised",
     *   @OA\Response(response=200, description="OK",
     *     @OA\JsonContent(
     *       @OA\Property(property="installed",        type="boolean"),
     *       @OA\Property(property="version",          type="string"),
     *       @OA\Property(property="php_version",      type="string"),
     *       @OA\Property(property="lock_created_at",  type="string", nullable=true, format="date-time"),
     *       @OA\Property(property="locale",           type="string"),
     *     )
     *   )
     * )
     */
    public function status(): JsonResponse
    {
        $lockPath = storage_path('install.lock');
        $installed = is_file($lockPath);

        $installedAt = null;
        $installerVersion = null;
        if ($installed) {
            $raw = @file_get_contents($lockPath);
            if ($raw !== false) {
                $data = json_decode($raw, true);
                if (is_array($data)) {
                    $installedAt = $data['installed_at'] ?? null;
                    $installerVersion = $data['installer_version'] ?? null;
                }
            }
        }

        return response()->json([
            'installed'       => $installed,
            'version'         => (string) config('app.version', $installerVersion ?? '1.0.1'),
            'php_version'     => PHP_VERSION,
            'lock_created_at' => $installedAt,
            'locale'          => (string) config('app.locale', 'ko'),
        ]);
    }
}
