package com.hiveops.guide.controller;

import com.hiveops.guide.dto.GuideDtos.ModuleView;
import com.hiveops.guide.dto.GuideDtos.NavApp;
import com.hiveops.guide.service.MarkdownGuideService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Read-only guide API backed by markdown files. Internal-audience content is only
 * returned to admin roles (MSP_ADMIN / BCOS_ADMIN); everyone else sees customer content.
 */
@RestController
@RequestMapping("/api/v1/guide")
@RequiredArgsConstructor
public class GuideController {

    private final MarkdownGuideService service;

    @GetMapping("/nav")
    public List<NavApp> nav(Authentication auth) {
        return service.nav(isInternal(auth), isBcos(auth));
    }

    @GetMapping("/modules/{module}")
    public ResponseEntity<ModuleView> module(@PathVariable String module, Authentication auth) {
        return service.module(module, isInternal(auth), isBcos(auth))
                .map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    private boolean isInternal(Authentication auth) {
        if (auth == null) return false;
        return auth.getAuthorities().stream()
                .map(a -> a.getAuthority())
                .anyMatch(a -> a.equals("ROLE_MSP_ADMIN") || a.equals("ROLE_BCOS_ADMIN"));
    }

    /** BCOS_ADMIN only — gates the strictest tier (audience: bcos), e.g. the Processes section. */
    private boolean isBcos(Authentication auth) {
        if (auth == null) return false;
        return auth.getAuthorities().stream()
                .map(a -> a.getAuthority())
                .anyMatch(a -> a.equals("ROLE_BCOS_ADMIN"));
    }
}
