package <%= packageName %>.controller;

import <%= packageName %>.dto.<%= entityName %>Dto;
import <%= packageName %>.dto.<%= entityName %>Filter;
import <%= packageName %>.service.<%= entityName %>Service;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * REST controller for {@link <%= packageName %>.entity.<%= entityName %>}.
 * This layer is intentionally thin — all business logic lives in the service.
 */
@RestController
@RequestMapping("/api/v1/<%= entityNameLower %>s")
@RequiredArgsConstructor
public class <%= entityName %>Controller {

    private final <%= entityName %>Service service;

    /**
     * GET /api/v1/<%= entityNameLower %>s
     * Supports pagination: ?page=0&size=20&sort=id,desc
     * Supports filtering: ?<%= fields[0] ? fields[0].name : 'field' %>=value (any field in <%= entityName %>Filter)
     */
    @GetMapping
    public ResponseEntity<Page<<%= entityName %>Dto>> getAll(
            @ModelAttribute <%= entityName %>Filter filter,
            @PageableDefault(size = 20, sort = "id", direction = Sort.Direction.DESC) Pageable pageable
    ) {
        return ResponseEntity.ok(service.findAll(filter, pageable));
    }

    @GetMapping("/{id}")
    public ResponseEntity<<%= entityName %>Dto> getById(@PathVariable Long id) {
        return service.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public ResponseEntity<<%= entityName %>Dto> create(@Valid @RequestBody <%= entityName %>Dto dto) {
        return ResponseEntity.status(HttpStatus.CREATED).body(service.create(dto));
    }

    @PutMapping("/{id}")
    public ResponseEntity<<%= entityName %>Dto> update(
            @PathVariable Long id,
            @Valid @RequestBody <%= entityName %>Dto dto
    ) {
        return service.update(id, dto)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        return service.deleteById(id)
                ? ResponseEntity.noContent().build()
                : ResponseEntity.notFound().build();
    }
}
