package com.pharmacopoeia.controller;

import com.pharmacopoeia.service.DrugService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/v1/drug")
public class DrugController {

    private final DrugService drugService;

    public DrugController(DrugService drugService) {
        this.drugService = drugService;
    }

    @GetMapping("/search")
    public ResponseEntity<Map<String, Object>> search(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String category,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int pageSize) {
        return ResponseEntity.ok(drugService.searchDrugs(keyword, category, page, pageSize));
    }

    @GetMapping("/{drugId}")
    public ResponseEntity<Map<String, Object>> getDetail(@PathVariable String drugId) {
        var detail = drugService.getDrugDetail(drugId);
        if (detail == null) {
            return ResponseEntity.status(404).body(Map.of("error", "Drug not found"));
        }
        return ResponseEntity.ok(Map.of("data", detail));
    }

    @GetMapping("/category/tree")
    public ResponseEntity<Map<String, Object>> getCategoryTree() {
        return ResponseEntity.ok(Map.of("tree", drugService.getCategoryTree()));
    }
}
