package org.raddatz.familienarchiv.user;

import jakarta.validation.Valid;
import org.raddatz.familienarchiv.user.ForgotPasswordRequest;
import org.raddatz.familienarchiv.user.InvitePrefillDTO;
import org.raddatz.familienarchiv.user.RegisterRequest;
import org.raddatz.familienarchiv.user.ResetPasswordRequest;
import org.raddatz.familienarchiv.user.AppUser;
import org.raddatz.familienarchiv.user.InviteToken;
import org.raddatz.familienarchiv.user.InviteService;
import org.raddatz.familienarchiv.user.PasswordResetService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import lombok.RequiredArgsConstructor;

@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {

    private final PasswordResetService passwordResetService;
    private final InviteService inviteService;

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

    @PostMapping("/forgot-password")
    public ResponseEntity<Void> forgotPassword(@RequestBody ForgotPasswordRequest request) {
        passwordResetService.requestReset(request.getEmail(), appBaseUrl);
        // Always return 204 — never disclose whether the email exists
        return ResponseEntity.noContent().build();
    }

    @PostMapping("/reset-password")
    public ResponseEntity<Void> resetPassword(@RequestBody ResetPasswordRequest request) {
        passwordResetService.resetPassword(request);
        return ResponseEntity.noContent().build();
    }

    @GetMapping("/invite/{code}")
    public InvitePrefillDTO getInvitePrefill(@PathVariable String code) {
        InviteToken token = inviteService.validateCode(code);
        return new InvitePrefillDTO(
                token.getPrefillFirstName(),
                token.getPrefillLastName(),
                token.getPrefillEmail()
        );
    }

    @PostMapping("/register")
    public ResponseEntity<AppUser> register(@Valid @RequestBody RegisterRequest request) {
        AppUser user = inviteService.redeemInvite(request);
        return ResponseEntity.status(HttpStatus.CREATED).body(user);
    }
}
