package net.siegeln.cameleer.saas.config;

import net.siegeln.cameleer.saas.identity.LogtoManagementClient;
import net.siegeln.cameleer.saas.tenant.TenantService;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
public class MeController {

    private final TenantService tenantService;
    private final LogtoManagementClient logtoClient;

    public MeController(TenantService tenantService, LogtoManagementClient logtoClient) {
        this.tenantService = tenantService;
        this.logtoClient = logtoClient;
    }

    @GetMapping("/api/me")
    public ResponseEntity<Map<String, Object>> me(Authentication authentication) {
        if (!(authentication instanceof JwtAuthenticationToken jwtAuth)) {
            return ResponseEntity.status(401).build();
        }

        Jwt jwt = jwtAuth.getToken();
        String userId = jwt.getSubject();

        String orgId = jwt.getClaimAsString("organization_id");

        if (orgId != null) {
            var tenant = tenantService.getByLogtoOrgId(orgId).orElse(null);
            List<Map<String, Object>> tenants = tenant != null
                    ? List.of(Map.<String, Object>of(
                            "id", tenant.getId().toString(),
                            "name", tenant.getName(),
                            "slug", tenant.getSlug(),
                            "logtoOrgId", tenant.getLogtoOrgId()))
                    : List.of();

            return ResponseEntity.ok(Map.of(
                    "userId", userId,
                    "tenants", tenants));
        }

        List<Map<String, String>> logtoOrgs = logtoClient.getUserOrganizations(userId);
        List<Map<String, Object>> tenants = logtoOrgs.stream()
                .map(org -> tenantService.getByLogtoOrgId(org.get("id"))
                        .map(t -> Map.<String, Object>of(
                                "id", t.getId().toString(),
                                "name", t.getName(),
                                "slug", t.getSlug(),
                                "logtoOrgId", t.getLogtoOrgId()))
                        .orElse(null))
                .filter(t -> t != null)
                .toList();

        return ResponseEntity.ok(Map.of(
                "userId", userId,
                "tenants", tenants));
    }
}
