package com.walkguide.controller;

import com.walkguide.dto.ApiResponse;
import com.walkguide.dto.request.*;
import com.walkguide.dto.response.AuthDataResponse;
import com.walkguide.security.SecurityHelper;
import com.walkguide.service.AuthService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

    private final AuthService authService;

    /** Health-check — digunakan Flutter ServerConnectScreen */
    @GetMapping("/ping")
    public ResponseEntity<ApiResponse<String>> ping() {
        return ResponseEntity.ok(ApiResponse.ok("pong", "Server aktif"));
    }

    @PostMapping("/register")
    public ResponseEntity<ApiResponse<AuthDataResponse>> register(
            @Valid @RequestBody RegisterRequest req) {
        return ResponseEntity.ok(ApiResponse.ok(authService.register(req), "Registrasi berhasil"));
    }

    @PostMapping("/login")
    public ResponseEntity<ApiResponse<AuthDataResponse>> login(
            @Valid @RequestBody LoginRequest req) {
        return ResponseEntity.ok(ApiResponse.ok(authService.login(req), "Login berhasil"));
    }

    @PostMapping("/refresh")
    public ResponseEntity<ApiResponse<AuthDataResponse>> refresh(
            @RequestBody RefreshTokenRequest req) {
        return ResponseEntity.ok(ApiResponse.ok(
                authService.refreshToken(req.getRefreshToken()), "Token diperbarui"));
    }

    @PostMapping("/logout")
    public ResponseEntity<ApiResponse<Void>> logout() {
        authService.logout(SecurityHelper.getCurrentUserId());
        return ResponseEntity.ok(ApiResponse.ok(null, "Logout berhasil"));
    }

    @PutMapping("/fcm-token")
    public ResponseEntity<ApiResponse<Void>> updateFcmToken(
            @RequestBody FcmTokenRequest req) {
        authService.updateFcmToken(SecurityHelper.getCurrentUserId(), req.getFcmToken());
        return ResponseEntity.ok(ApiResponse.ok(null, "FCM token diperbarui"));
    }
}
