package dp.kotul.jwtapi.controller

import dp.kotul.jwt.model.User
import dp.kotul.jwtapi.model.InstanceSession
import dp.kotul.jwtapi.model.Jwt
import dp.kotul.jwtapi.service.JwtService
import dp.kotul.jwtapi.service.UserService
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiParam
import io.swagger.annotations.ApiResponse
import io.swagger.annotations.ApiResponses
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
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

@Api(tags = ["Jwt"], description = "Provides API for JWT token operations")
@RestController
@RequestMapping("/jwt")
class JwtController(val userService: UserService, val jwtService: JwtService) {

    @ApiOperation(value = "Generate JWT token", notes = "Generate JWT token for session ID and instance ID")
    @ApiResponses(
        ApiResponse(code = 200, message = "Valid request. JWT authorization bearer is returned in response body"),
        ApiResponse(code = 401, message = "Invalid combination of session id and instance id")
    )
    @PostMapping("/generate")
    fun generate(
        @ApiParam(value = "JSON object containing instance ID and session ID.", required = true) @RequestBody instanceSession: InstanceSession
    ): ResponseEntity<Jwt> {
        return getResult(userService.getUserBySession(instanceSession))
    }

    @ApiOperation(value = "Parse JWT token", notes = "Validate and parse user from JWT token")
    @ApiResponses(
        ApiResponse(code = 200, message = "Valid request. Claims are returned in response body"),
        ApiResponse(code = 401, message = "Invalid token")
    )
    @PostMapping("/parse")
    fun parseJwtToken(
        @ApiParam(value = "JSON object containing JWT token.", required = true) @RequestBody jwtToken: Jwt
    ): ResponseEntity<Map<String, Any>> {
        return jwtService.parseJwt(jwtToken.jwt)
    }

    private fun getResult(user: User?): ResponseEntity<Jwt> {
        if (user == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build()
        }

        return ResponseEntity.ok(Jwt(jwtService.generateJwt(user)))
    }
}
