package com.pressing.modules.discount;

import com.pressing.common.dto.PageResponse;
import com.pressing.modules.discount.dto.DiscountDtos.DiscountRequest;
import com.pressing.modules.discount.dto.DiscountDtos.DiscountResponse;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/v1/discounts")
public class DiscountController {

    private final DiscountService discountService;

    public DiscountController(DiscountService discountService) {
        this.discountService = discountService;
    }

    // LISTE ET HISTORIQUE DES RÉDUCTIONS
    @GetMapping
    public PageResponse<DiscountResponse> search(
            @RequestParam(required = false) String q,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "50") int size
    ) {
        return discountService.searchDiscounts(q, page, size);
    }

    // BONUS ACTIF POUR UN CLIENT DONNÉ (pré-remplissage automatique au dépôt)
    @GetMapping("/active-for-customer/{customerId}")
    public ResponseEntity<DiscountResponse> activeForCustomer(@PathVariable Long customerId) {
        DiscountResponse dto = discountService.findActiveDiscountForCustomer(customerId);
        return dto != null ? ResponseEntity.ok(dto) : ResponseEntity.noContent().build();
    }

    // ATTRIBUTION D'UNE RÉDUCTION / BONUS
    @PostMapping
    public DiscountResponse create(@Valid @RequestBody DiscountRequest req) {
        return discountService.createDiscount(req);
    }

    // MODIFICATION DE LA DATE OU DU TAUX DE RÉDUCTION
    @PutMapping("/{id}")
    public DiscountResponse update(@PathVariable Long id, @Valid @RequestBody DiscountRequest req) {
        return discountService.updateDiscount(id, req);
    }

    // SUPPRESSION D'UNE RÉDUCTION
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public void delete(@PathVariable Long id) {
        discountService.deleteDiscount(id);
    }
}