package com.pressing.modules.invoice;

import com.pressing.modules.invoice.dto.InvoiceDtos.InvoiceRequest;
import jakarta.validation.Valid;
import java.time.LocalDate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1/invoices")
public class InvoiceController {

    private final InvoiceService invoiceService;

    public InvoiceController(InvoiceService invoiceService) {
        this.invoiceService = invoiceService;
    }

    @GetMapping
    public Object search(
            @RequestParam(required = false) String q,
            @RequestParam(required = false) LocalDate from,
            @RequestParam(required = false) LocalDate to,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "50") int size
    ) {
        return invoiceService.search(q, from, to, status, page, size);
    }

    @GetMapping("/{id}")
    public Object get(@PathVariable Long id) {
        return invoiceService.get(id);
    }

    @GetMapping("/by-number/{number}")
    public Object byNumber(@PathVariable String number) {
        return invoiceService.getByNumber(number);
    }

    @PostMapping
    public Object create(@Valid @RequestBody InvoiceRequest req) {
        return invoiceService.create(req);
    }

    @PutMapping("/{id}")
    public Object update(@PathVariable Long id, @Valid @RequestBody InvoiceRequest req) {
        return invoiceService.update(id, req);
    }

    @PostMapping("/{id}/validate")
    public Object validate(@PathVariable Long id) {
        return invoiceService.validate(id);
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public void delete(@PathVariable Long id) {
        invoiceService.delete(id);
    }
}
