package online.wesal.wesal.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import online.wesal.wesal.dto.CreateUserRequest;
import online.wesal.wesal.dto.LoginRequest;
import online.wesal.wesal.dto.LoginResponse;
import online.wesal.wesal.dto.UpdateUserRequest;
import online.wesal.wesal.dto.UsernameSelectionRequest;
import online.wesal.wesal.entity.User;
import online.wesal.wesal.service.AuthService;
import online.wesal.wesal.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/")
@CrossOrigin(origins = "*")
@Tag(name = "Authentication", description = "Authentication endpoints")
public class AuthController {
    
    @Autowired
    private AuthService authService;
    
    @Autowired
    private UserService userService;
    
    @GetMapping("/")
    @Operation(summary = "Health check", description = "Returns API status")
    public ResponseEntity<Map<String, Integer>> healthCheck() {
        return ResponseEntity.ok(Map.of("status", 200));
    }
    
    @PostMapping("/login")
    @Operation(summary = "User login", description = "Authenticate user with email or username and return JWT token")
    public ResponseEntity<LoginResponse> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            String token = authService.authenticate(loginRequest.getEmailOrUsername(), loginRequest.getPassword());
            return ResponseEntity.ok(new LoginResponse(token));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    @PostMapping("/set-username")
    @Operation(summary = "Set username", description = "Set username for authenticated user (can only be done once)")
    public ResponseEntity<User> setUsername(@Valid @RequestBody UsernameSelectionRequest request) {
        try {
            User user = userService.setUsername(request.getUsername());
            return ResponseEntity.ok(user);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    @GetMapping("/getUser")
    @Operation(summary = "Get current user", description = "Returns the authenticated user's details")
    public ResponseEntity<User> getUser() {
        try {
            User user = userService.getCurrentUser();
            return ResponseEntity.ok(user);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    @PostMapping("/updateUser")
    @Operation(summary = "Update user information", description = "Update authenticated user's fcmToken, displayName, avatar, or password")
    public ResponseEntity<Map<String, Object>> updateUser(@Valid @RequestBody UpdateUserRequest request) {
        try {
            User user = userService.updateUser(
                request.getFcmToken(),
                request.getDisplayName(),
                request.getAvatar(),
                request.getPassword()
            );
            return ResponseEntity.ok(Map.of("status", 200, "user", user));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(Map.of("status", 400, "message", e.getMessage()));
        }
    }
    
    @PostMapping("/admin/createUser")
    @Operation(summary = "Create new user (Admin only)", description = "Creates a new user - requires admin privileges")
    public ResponseEntity<?> createUser(@Valid @RequestBody CreateUserRequest request) {
        try {
            User user = userService.createUser(request.getEmail(), request.getPassword(), request.getDisplayName());
            return ResponseEntity.ok(user);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }
}