package com.example.demo.supplier.controller;

import com.example.demo.common.AppDefaultsProperties;
import com.example.demo.supplier.dto.SupplierDtos;
import com.example.demo.supplier.service.SupplierService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/suppliers")
public class SupplierController {

    private final SupplierService supplierService;
    private final AppDefaultsProperties defaults;

    public SupplierController(SupplierService supplierService, AppDefaultsProperties defaults) {
        this.supplierService = supplierService;
        this.defaults = defaults;
    }

    @GetMapping
    public ResponseEntity<?> search(@RequestHeader(name = "X-Shop-Id", required = false) Long shopId,
                                    @RequestParam(name = "kw", required = false) String kw,
                                    @RequestParam(name = "debtOnly", required = false, defaultValue = "false") boolean debtOnly,
                                    @RequestParam(name = "page", defaultValue = "1") int page,
                                    @RequestParam(name = "size", defaultValue = "50") int size) {
        Long sid = (shopId == null ? defaults.getShopId() : shopId);
        return ResponseEntity.ok(supplierService.search(sid, kw, debtOnly, Math.max(0, page-1), size));
    }

    @PostMapping
    public ResponseEntity<?> create(@RequestHeader(name = "X-Shop-Id", required = false) Long shopId,
                                    @RequestHeader(name = "X-User-Id", required = false) Long userId,
                                    @RequestBody SupplierDtos.CreateOrUpdateSupplierRequest req) {
        Long sid = (shopId == null ? defaults.getShopId() : shopId);
        Long uid = (userId == null ? defaults.getUserId() : userId);
        Long id = supplierService.create(sid, uid, req);
        java.util.Map<String,Object> body = new java.util.HashMap<>();
        body.put("id", id);
        return ResponseEntity.ok(body);
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> update(@PathVariable("id") Long id,
                                    @RequestHeader(name = "X-Shop-Id", required = false) Long shopId,
                                    @RequestHeader(name = "X-User-Id", required = false) Long userId,
                                    @RequestBody SupplierDtos.CreateOrUpdateSupplierRequest req) {
        Long sid = (shopId == null ? defaults.getShopId() : shopId);
        Long uid = (userId == null ? defaults.getUserId() : userId);
        supplierService.update(id, sid, uid, req);
        return ResponseEntity.ok().build();
    }
}


