package br.gov.sigefp.admin.api;

import br.gov.sigefp.admin.api.dto.AssignRolesDTO;
import br.gov.sigefp.admin.api.dto.UserAccountDTO;
import br.gov.sigefp.admin.service.UserService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

/**
 * Controller REST para gestão de utilizadores.
 */
@RestController
@RequestMapping("/api/admin/users")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @GetMapping
    public ResponseEntity<?> findAll(
            @RequestParam(value = "page", defaultValue = "0") int page,
            @RequestParam(value = "size", defaultValue = "20") int size,
            @RequestParam(value = "sortBy", required = false) String sortBy,
            @RequestParam(value = "sortDirection", required = false, defaultValue = "ASC") String sortDirection) {
        try {
            Sort sort = sortBy != null && !sortBy.isEmpty()
                ? Sort.by(Sort.Direction.fromString(sortDirection), sortBy)
                : Sort.by(Sort.Direction.ASC, "createdAt");
            
            Pageable pageable = PageRequest.of(page, size, sort);
            Page<UserAccountDTO> result = userService.findAll(pageable);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Erro ao buscar utilizadores: " + e.getMessage());
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<UserAccountDTO> findById(@PathVariable("id") UUID id) {
        try {
            UserAccountDTO dto = userService.findById(id);
            return ResponseEntity.ok(dto);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.notFound().build();
        }
    }

    @PostMapping
    public ResponseEntity<UserAccountDTO> create(@Valid @RequestBody UserAccountDTO dto) {
        try {
            UserAccountDTO created = userService.create(dto);
            return ResponseEntity.status(HttpStatus.CREATED).body(created);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<UserAccountDTO> update(
            @PathVariable("id") UUID id,
            @Valid @RequestBody UserAccountDTO dto) {
        try {
            UserAccountDTO updated = userService.update(id, dto);
            return ResponseEntity.ok(updated);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.notFound().build();
        }
    }

    @PostMapping("/{id}/roles")
    public ResponseEntity<Void> assignRoles(
            @PathVariable("id") UUID id,
            @Valid @RequestBody AssignRolesDTO dto) {
        try {
            userService.assignRoles(id, dto.getRoleIds());
            return ResponseEntity.ok().build();
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        }
    }
}
