package com.mvrent.carrental.controller;

import com.mvrent.carrental.service.ConfigService;
import com.mvrent.carrental.web.CategoryDto;
import com.mvrent.carrental.web.CategoryForm;
import lombok.RequiredArgsConstructor;
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.Map;

/** JSON API backing the AJAX category master screen. */
@RestController
@RequestMapping("/admin/api/categories")
@RequiredArgsConstructor
@PreAuthorize("hasRole('ADMIN') or hasAuthority('MANAGE_CONFIG')")
public class AdminCategoryApiController {

    private final ConfigService configService;

    @GetMapping
    public List<CategoryDto> list() {
        return configService.allCategories().stream().map(CategoryDto::from).toList();
    }

    @PostMapping
    public ResponseEntity<?> add(@RequestBody CategoryForm f) {
        if (f.type() == null) {
            return ResponseEntity.badRequest().body(Map.of("ok", false, "message", "Type is required"));
        }
        if (f.name() == null || f.name().isBlank()) {
            return ResponseEntity.badRequest().body(Map.of("ok", false, "message", "Name is required"));
        }
        try {
            return ResponseEntity.ok(Map.of("ok", true,
                    "category", CategoryDto.from(configService.addCategory(f.type(), f.name().trim(), f.description()))));
        } catch (IllegalArgumentException ex) {
            return ResponseEntity.badRequest().body(Map.of("ok", false, "message", ex.getMessage()));
        }
    }

    @PostMapping("/{id}/toggle")
    public ResponseEntity<?> toggle(@PathVariable Long id) {
        configService.toggleCategory(id);
        return ResponseEntity.ok(Map.of("ok", true));
    }

    @PostMapping("/{id}/delete")
    public ResponseEntity<?> delete(@PathVariable Long id) {
        try {
            configService.deleteCategory(id);
            return ResponseEntity.ok(Map.of("ok", true));
        } catch (Exception ex) {
            return ResponseEntity.badRequest().body(Map.of("ok", false,
                    "message", "Cannot delete — category is in use. Disable it instead."));
        }
    }
}
