package de.cannamanage.api.controller;

import de.cannamanage.api.dto.stock.BatchResponse;
import de.cannamanage.api.dto.stock.CreateBatchRequest;
import de.cannamanage.domain.entity.Batch;
import de.cannamanage.domain.enums.BatchStatus;
import de.cannamanage.service.repository.BatchRepository;
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.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/v1/stock/batches")
@RequiredArgsConstructor
@Tag(name = "Stock", description = "Batch and inventory management")
public class StockController {

    private final BatchRepository batchRepository;

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

    @GetMapping("/{id}")
    @Operation(summary = "Get batch by ID")
    @PreAuthorize("hasRole('ADMIN') or @staffPermissions.has(authentication, T(de.cannamanage.domain.enums.StaffPermission).VIEW_STOCK)")
    public ResponseEntity<BatchResponse> getBatch(@PathVariable UUID id) {
        Batch batch = batchRepository.findById(id)
                .orElseThrow(() -> new org.springframework.web.server.ResponseStatusException(
                        HttpStatus.NOT_FOUND, "Batch not found"));
        return ResponseEntity.ok(toResponse(batch));
    }

    @PostMapping
    @Operation(summary = "Create a new batch", description = "Registers a new cannabis batch in inventory")
    @PreAuthorize("hasRole('ADMIN') or @staffPermissions.has(authentication, T(de.cannamanage.domain.enums.StaffPermission).RECORD_STOCK_IN)")
    public ResponseEntity<BatchResponse> createBatch(@Valid @RequestBody CreateBatchRequest request) {
        Batch batch = new Batch();
        batch.setStrainId(request.strainId());
        batch.setQuantityGrams(request.quantityGrams());
        batch.setHarvestDate(request.harvestDate());
        batch.setBatchCode(request.batchCode());
        batch.setStatus(BatchStatus.AVAILABLE);

        Batch saved = batchRepository.save(batch);
        return ResponseEntity.status(HttpStatus.CREATED).body(toResponse(saved));
    }

    private BatchResponse toResponse(Batch b) {
        return new BatchResponse(
                b.getId(),
                b.getStrainId(),
                b.getQuantityGrams(),
                b.getHarvestDate(),
                b.getBatchCode(),
                b.getStatus(),
                b.isContaminationFlag()
        );
    }
}
