package io.cameleer.server.app.security;

import io.cameleer.server.app.dto.AuthCapabilitiesResponse;
import io.cameleer.server.core.security.OidcConfig;
import io.cameleer.server.core.security.OidcConfigRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/**
 * Reports auth capabilities so the SPA renders the login page deterministically
 * instead of inferring from {@code GET /api/v1/auth/oidc/config} 200/404.
 *
 * <p>Unauthenticated by design — the SPA calls this before any sign-in attempt.
 * Inherits permit-all from the {@code /api/v1/auth/**} matcher in
 * {@link SecurityConfig}.
 *
 * <p>Future deferred work (issue #154) extends this same payload with MFA
 * enrollment URL and password-reset URL fields.
 */
@RestController
@RequestMapping("/api/v1/auth")
@Tag(name = "Authentication", description = "Login and token refresh endpoints")
public class AuthCapabilitiesController {

    private final OidcConfigRepository oidcConfigRepository;

    public AuthCapabilitiesController(OidcConfigRepository oidcConfigRepository) {
        this.oidcConfigRepository = oidcConfigRepository;
    }

    @GetMapping("/capabilities")
    @Operation(summary = "Auth capabilities for the SPA login page")
    @ApiResponse(responseCode = "200", description = "Capabilities resolved")
    public ResponseEntity<AuthCapabilitiesResponse> getCapabilities() {
        Optional<OidcConfig> config = oidcConfigRepository.find();
        boolean oidcEnabled = config.isPresent() && config.get().enabled();
        String providerName = oidcEnabled
                ? OidcProviderNameDeriver.deriveName(config.get().issuerUri())
                : "";

        var oidc = new AuthCapabilitiesResponse.Oidc(oidcEnabled, providerName, oidcEnabled);
        var local = new AuthCapabilitiesResponse.LocalAccounts(true, oidcEnabled);
        return ResponseEntity.ok(new AuthCapabilitiesResponse(oidc, local));
    }
}
