<?php

namespace App\Http\Controllers\Installer;

use App\Http\Controllers\Controller;
use App\Installer\Services\InstallationManager;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\View\View;

/**
 * Installation Controller
 * Handles Step 4: Demo Data & Installation Completion
 */
class InstallationController extends Controller
{
    public function __construct(
        private InstallationManager $installationManager
    ) {}

    /**
     * Display demo data selection page
     */
    public function index(): View
    {
        return view('installer.step4', [
            'step' => 4,
            'totalSteps' => 4,
        ]);
    }

    /**
     * Complete installation
     */
    public function complete(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'admin_email' => 'required|email',
            'admin_password' => 'required|string|min:8',
            'import_demo_data' => 'nullable|boolean',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors(),
            ], 422);
        }

        try {
            // Seed default roles first (required for admin user)
            Artisan::call('db:seed', [
                '--class' => 'RoleSeeder',
                '--force' => true,
            ]);

            // Create admin user
            $admin = $this->installationManager->createAdminUser(
                $request->admin_email,
                $request->admin_password
            );

            // Import demo data if requested
            if ($request->boolean('import_demo_data')) {
                $this->installationManager->importDemoData();
            }

            // Second pass: ensure public/storage symlink after demo uploads may exist (non-fatal if it fails)
            $linkExit = Artisan::call('storage:link', ['--force' => true]);
            if ($linkExit !== 0) {
                Log::warning('Installer step 4: storage:link exited non-zero', ['code' => $linkExit]);
            }

            // Mark as installed
            $this->installationManager->markAsInstalled();

            return response()->json([
                'success' => true,
                'message' => 'Installation completed successfully',
                'admin' => [
                    'email' => $admin->email,
                    'password' => $request->admin_password,
                ],
            ]);
        } catch (\Exception $e) {
            Log::error('Installation failed: '.$e->getMessage(), [
                'trace' => $e->getTraceAsString(),
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Installation failed: '.$e->getMessage(),
            ], 500);
        }
    }

    /**
     * Display installation success page
     */
    public function success(Request $request): View
    {
        $adminEmail = $request->get('email');
        $adminPassword = $request->get('password');

        return view('installer.success', [
            'adminEmail' => $adminEmail,
            'adminPassword' => $adminPassword,
        ]);
    }
}
