package de.cannamanage.api.controller;

import de.cannamanage.api.dto.distribution.CreateDistributionRequest;
import de.cannamanage.api.dto.distribution.DistributionResponse;
import de.cannamanage.domain.entity.Distribution;
import de.cannamanage.service.ComplianceService;
import de.cannamanage.service.repository.DistributionRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/v1/distributions")
@RequiredArgsConstructor
@Tag(name = "Distributions", description = "Cannabis distribution recording (CanG §26)")
public class DistributionController {

    private final DistributionRepository distributionRepository;
    private final ComplianceService complianceService;

    @GetMapping
    @Operation(summary = "List all distributions", description = "Returns all distribution records for the current tenant")
    @PreAuthorize("hasRole('ADMIN') or @staffPermissions.has(authentication, T(de.cannamanage.domain.enums.StaffPermission).RECORD_DISTRIBUTION)")
    public ResponseEntity<List<DistributionResponse>> listDistributions() {
        List<DistributionResponse> distributions = distributionRepository.findAll().stream()
                .map(this::toResponse)
                .toList();
        return ResponseEntity.ok(distributions);
    }

    @PostMapping
    @Operation(summary = "Record a distribution",
            description = "Records a cannabis distribution after compliance checks pass (CanG §19)")
    @PreAuthorize("hasRole('ADMIN') or @staffPermissions.has(authentication, T(de.cannamanage.domain.enums.StaffPermission).RECORD_DISTRIBUTION)")
    public ResponseEntity<DistributionResponse> createDistribution(
            @Valid @RequestBody CreateDistributionRequest request,
            Authentication authentication) {

        // Run compliance checks — throws QuotaExceededException if violated
        complianceService.checkDistributionAllowed(
                request.memberId(), request.batchId(), request.quantityGrams());

        UUID recordedBy = (UUID) authentication.getPrincipal();

        Distribution distribution = new Distribution();
        distribution.setMemberId(request.memberId());
        distribution.setBatchId(request.batchId());
        distribution.setQuantityGrams(request.quantityGrams());
        distribution.setDistributedAt(Instant.now());
        distribution.setRecordedBy(recordedBy);
        distribution.setNotes(request.notes());

        Distribution saved = distributionRepository.save(distribution);
        return ResponseEntity.status(HttpStatus.CREATED).body(toResponse(saved));
    }

    private DistributionResponse toResponse(Distribution d) {
        return new DistributionResponse(
                d.getId(),
                d.getMemberId(),
                d.getBatchId(),
                d.getQuantityGrams(),
                d.getDistributedAt(),
                d.getRecordedBy(),
                d.getNotes()
        );
    }
}
