<?php

namespace Modules\ExternalSystem\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Modules\ExternalSystem\Entities\ExternalSystem;
use Modules\ExternalSystem\Exceptions\ExternalSystemLaunchException;
use Modules\ExternalSystem\Services\ExternalSystemLaunchService;
use Modules\ExternalSystem\Transformers\ExternalSystemResource;

class ExternalSystemController extends Controller
{
    public function __construct(
        protected ExternalSystemLaunchService $launchService,
    ) {}

    public function index(): JsonResponse
    {
        $systems = ExternalSystem::query()
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get();

        return response()->json([
            'success' => true,
            'data' => ExternalSystemResource::collection($systems),
        ]);
    }

    public function show(string $id): JsonResponse
    {
        $system = ExternalSystem::query()->find($id);

        if (! $system) {
            return response()->json([
                'success' => false,
                'message' => 'Sistem luaran tidak dijumpai.',
                'data' => null,
            ], 404);
        }

        return response()->json([
            'success' => true,
            'data' => new ExternalSystemResource($system),
        ]);
    }

    public function launch(Request $request, string $code): JsonResponse
    {
        try {
            $result = $this->launchService->launch($request->user(), $code);

            return response()->json([
                'success' => true,
                'message' => 'SSO berjaya dijana.',
                'data' => $result,
            ]);
        } catch (ExternalSystemLaunchException $exception) {
            return response()->json([
                'success' => false,
                'message' => $exception->getMessage(),
                'code' => $exception->errorCode,
                'data' => null,
            ], $exception->status);
        } catch (\Throwable $exception) {
            Log::error('Failed to launch external system SSO.', [
                'code' => $code,
                'user_id' => $request->user()?->id,
                'message' => $exception->getMessage(),
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Gagal membuka sistem luaran. Sila cuba lagi.',
                'code' => 'external_system_launch_failed',
                'data' => null,
            ], 500);
        }
    }
}
