package com.petshop.backend.controller;

import com.petshop.backend.dto.common.BulkDeleteRequest;
import com.petshop.backend.dto.user.UserRequest;
import com.petshop.backend.dto.user.UserResponse;
import com.petshop.backend.entity.User;
import com.petshop.backend.service.UserService;
import jakarta.validation.Valid;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/v1/customers")
@PreAuthorize("hasAnyRole('STAFF', 'ADMIN')")
public class CustomerController {

    private final UserService userService;

    public CustomerController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public ResponseEntity<Page<UserResponse>> getAllCustomers(
            @RequestParam(required = false) String q,
            Pageable pageable) {
        return ResponseEntity.ok(userService.getAllUsers(q, "CUSTOMER", pageable));
    }

    @GetMapping("/{id}")
    public ResponseEntity<UserResponse> getCustomerById(@PathVariable Long id) {
        return ResponseEntity.ok(userService.getUserById(id, User.Role.CUSTOMER));
    }

    @PostMapping
    public ResponseEntity<UserResponse> createCustomer(@Valid @RequestBody UserRequest request) {
        return ResponseEntity.status(HttpStatus.CREATED).body(userService.createUser(request, User.Role.CUSTOMER));
    }

    @PutMapping("/{id}")
    public ResponseEntity<UserResponse> updateCustomer(
            @PathVariable Long id,
            @Valid @RequestBody UserRequest request) {
        return ResponseEntity.ok(userService.updateUser(id, request, User.Role.CUSTOMER));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteCustomer(@PathVariable Long id) {
        userService.deleteUser(id, User.Role.CUSTOMER);
        return ResponseEntity.noContent().build();
    }

    @PostMapping("/bulk-delete")
    public ResponseEntity<Void> bulkDeleteCustomers(@Valid @RequestBody BulkDeleteRequest request) {
        userService.bulkDeleteUsers(request, User.Role.CUSTOMER);
        return ResponseEntity.noContent().build();
    }
}
