<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\DemoSandbox;
use App\Services\Demo\SandboxManager;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * Visitor-facing endpoints for the demo sandbox.
 *
 * All three routes assume the DemoMode middleware has already attached a
 * sandbox to the request — they are mounted under the demo middleware group
 * in routes/api.php. If demo mode is disabled (production), the routes
 * return a graceful 404-style response.
 */
class DemoController extends Controller
{
    public function __construct(private readonly SandboxManager $manager)
    {
    }

    /**
     * Current sandbox metadata: when it expires, what was seeded, who you are.
     */
    public function status(Request $request): JsonResponse
    {
        if (!config('demo.enabled')) {
            return response()->json(['error' => 'DEMO_DISABLED'], 404);
        }

        $sandbox = $this->resolveSandbox($request);
        if (!$sandbox) {
            return response()->json(['error' => 'SANDBOX_NOT_FOUND'], 404);
        }

        $user = $sandbox->adminUser;

        return response()->json([
            'sandbox' => [
                'id'              => $sandbox->id,
                'tenant_id'       => $sandbox->tenant_id,
                'expires_at'      => optional($sandbox->expires_at)->toIso8601String(),
                'last_active_at'  => optional($sandbox->last_active_at)->toIso8601String(),
                'ip_address'      => $sandbox->ip_address,
                'seeded'          => (bool) ($sandbox->meta['seeded'] ?? false),
            ],
            'user' => $user ? [
                'id'    => $user->id,
                'email' => $user->email,
                'name'  => $user->name,
            ] : null,
            'config' => [
                'ttl_hours'     => (int) config('demo.sandbox_ttl_hours', 24),
                'auto_login'    => (bool) config('demo.auto_login', true),
                'max_upload_mb' => (int) round(((int) config('demo.max_upload_bytes', 5_242_880)) / (1024 * 1024)),
            ],
        ]);
    }

    /**
     * Reset the visitor's sandbox: drop their changes, re-seed from base.
     */
    public function reset(Request $request): JsonResponse
    {
        if (!config('demo.enabled')) {
            return response()->json(['error' => 'DEMO_DISABLED'], 404);
        }

        $sandbox = $this->resolveSandbox($request);
        if (!$sandbox) {
            return response()->json(['error' => 'SANDBOX_NOT_FOUND'], 404);
        }

        $this->manager->reset($sandbox);

        return response()->json([
            'ok'         => true,
            'sandbox_id' => $sandbox->id,
            'reset_at'   => now()->toIso8601String(),
            'expires_at' => optional($sandbox->fresh()->expires_at)->toIso8601String(),
        ]);
    }

    /**
     * Static guided tour. Frontend renders this into a step-by-step modal.
     */
    public function guide(Request $request): JsonResponse
    {
        return response()->json([
            'steps' => [
                [
                    'id'    => 'admin',
                    'icon'  => '🛠️',
                    'title' => '관리자 패널',
                    'desc'  => '회원 / 게시판 / 페이지 / 메뉴를 직접 만들고 수정해 보세요.',
                    'route' => '/admin',
                ],
                [
                    'id'    => 'community',
                    'icon'  => '💬',
                    'title' => '커뮤니티',
                    'desc'  => '게시판에 글을 쓰고 댓글을 달아 보세요.',
                    'route' => '/community',
                ],
                [
                    'id'    => 'builder',
                    'icon'  => '🧱',
                    'title' => '페이지 빌더',
                    'desc'  => '블록을 드래그해서 페이지를 조립하고 즉시 공개합니다.',
                    'route' => '/builder',
                ],
                [
                    'id'    => 'customizer',
                    'icon'  => '🎨',
                    'title' => '커스터마이저',
                    'desc'  => '색·폰트·간격을 바꿔 사이트 외관을 실시간 미리보기.',
                    'route' => '/admin/customizer',
                ],
                [
                    'id'    => 'shop-ai',
                    'icon'  => '🛒',
                    'title' => '쇼핑몰 / AI 스튜디오',
                    'desc'  => '상품 등록부터 모의 결제, AI 콘텐츠 생성까지 한 번에.',
                    'route' => '/admin/shop',
                ],
            ],
            'note' => '데모 모드 — 모든 변경 사항은 24시간 후 자동 초기화됩니다.',
        ]);
    }

    protected function resolveSandbox(Request $request): ?DemoSandbox
    {
        $hash = $this->manager->hashIp((string) $request->ip());
        return DemoSandbox::query()->where('ip_hash', $hash)->first();
    }
}
