package de.cannamanage.api.controller;

import de.cannamanage.api.security.PortalPrincipal;
import de.cannamanage.service.PortalService;
import de.cannamanage.service.dto.portal.PortalDashboard;
import de.cannamanage.service.dto.portal.PortalDistributionHistory;
import de.cannamanage.service.dto.portal.PortalProfile;
import de.cannamanage.service.dto.portal.PortalQuota;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Member self-service portal — read-only JSON endpoints.
 * All data is scoped to the authenticated member via session principal.
 */
@RestController
@RequestMapping("/portal")
public class PortalController {

    private final PortalService portalService;

    public PortalController(PortalService portalService) {
        this.portalService = portalService;
    }

    /**
     * Dashboard: quota summary + recent distributions (last 5).
     */
    @GetMapping("/dashboard")
    public ResponseEntity<PortalDashboard> dashboard(@AuthenticationPrincipal PortalPrincipal principal) {
        PortalDashboard dashboard = portalService.getDashboard(principal.getTenantId(), principal.getMemberId());
        return ResponseEntity.ok(dashboard);
    }

    /**
     * Member's own profile.
     */
    @GetMapping("/me")
    public ResponseEntity<PortalProfile> profile(@AuthenticationPrincipal PortalPrincipal principal) {
        PortalProfile profile = portalService.getProfile(principal.getTenantId(), principal.getMemberId());
        return ResponseEntity.ok(profile);
    }

    /**
     * Current month quota status (daily + monthly, used/remaining).
     */
    @GetMapping("/quota")
    public ResponseEntity<PortalQuota> quota(@AuthenticationPrincipal PortalPrincipal principal) {
        PortalQuota quota = portalService.getQuota(principal.getTenantId(), principal.getMemberId());
        return ResponseEntity.ok(quota);
    }

    /**
     * Own distribution history, paginated.
     */
    @GetMapping("/distributions")
    public ResponseEntity<PortalDistributionHistory> distributions(
            @AuthenticationPrincipal PortalPrincipal principal,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        Pageable pageable = PageRequest.of(page, Math.min(size, 100));
        PortalDistributionHistory history = portalService.getDistributionHistory(
                principal.getTenantId(), principal.getMemberId(), pageable);
        return ResponseEntity.ok(history);
    }
}
