package cz.muni.fi.pa165.soccermanager.controllers;

import static cz.muni.fi.pa165.soccermanager.ApplicationConstants.API_URL;

import cz.muni.fi.pa165.soccermanager.annotation.CredentialsEndpoint;
import cz.muni.fi.pa165.soccermanager.dto.LoginResult;
import cz.muni.fi.pa165.soccermanager.dto.UserAuthenticateDto;
import cz.muni.fi.pa165.soccermanager.dto.request.CreateUserRequest;
import cz.muni.fi.pa165.soccermanager.security.AuthServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import javax.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Tag(name = "Auth ")
@RestController
@RequiredArgsConstructor
@RequestMapping(API_URL)
@CredentialsEndpoint
@CrossOrigin(origins = "*")
public class AuthController {

    private final AuthServiceImpl authService;

    @Operation(summary = "Authentication", description = "Method returns JWT for Bearer Authentication")
    @PostMapping("/login")
    public ResponseEntity<LoginResult> login(@Valid @RequestBody UserAuthenticateDto authenticateDto) {
        final var token = authService.performLogin(authenticateDto);
        return ResponseEntity.ok(token);
    }

    @Operation(summary = "Registration", description = "Method register user and returns JWT for Bearer Authentication")
    @PostMapping("/register")
    public ResponseEntity<LoginResult> register(@Valid @RequestBody CreateUserRequest request) {
        final var loginRequest = authService.registerUser(request);
        final var token = authService.performLogin(loginRequest);
        return ResponseEntity.ok(token);
    }

}
