package org.raddatz.familienarchiv.user;

import lombok.RequiredArgsConstructor;
import org.raddatz.familienarchiv.user.CreateInviteRequest;
import org.raddatz.familienarchiv.user.InviteListItemDTO;
import org.raddatz.familienarchiv.user.AppUser;
import org.raddatz.familienarchiv.security.Permission;
import org.raddatz.familienarchiv.security.RequirePermission;
import org.raddatz.familienarchiv.user.InviteService;
import org.raddatz.familienarchiv.user.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/invites")
@RequiredArgsConstructor
public class InviteController {

    private final InviteService inviteService;
    private final UserService userService;

    @Value("${app.base-url:http://localhost:3000}")
    private String appBaseUrl;

    @GetMapping
    @RequirePermission(Permission.ADMIN_USER)
    public List<InviteListItemDTO> listInvites(
            @RequestParam(value = "status", defaultValue = "active") String status) {
        boolean activeOnly = !"all".equalsIgnoreCase(status);
        return inviteService.listInvites(activeOnly, appBaseUrl);
    }

    @PostMapping
    @RequirePermission(Permission.ADMIN_USER)
    public ResponseEntity<InviteListItemDTO> createInvite(
            @RequestBody CreateInviteRequest request,
            @AuthenticationPrincipal UserDetails principal) {
        AppUser creator = userService.findByEmail(principal.getUsername());
        InviteListItemDTO created = inviteService.toListItemDTO(
                inviteService.createInvite(request, creator), appBaseUrl);
        return ResponseEntity.status(HttpStatus.CREATED).body(created);
    }

    @DeleteMapping("/{id}")
    @RequirePermission(Permission.ADMIN_USER)
    public ResponseEntity<Void> revokeInvite(@PathVariable UUID id) {
        inviteService.revokeInvite(id);
        return ResponseEntity.noContent().build();
    }
}
