package com.nisemoe.nise.controller

import com.nisemoe.generated.tables.references.SCORES
import com.nisemoe.nise.SimilarReplayEntry
import com.nisemoe.nise.SuspiciousScoreEntry
import com.nisemoe.nise.UserDetails
import com.nisemoe.nise.UserQueueDetails
import com.nisemoe.nise.database.ScoreService
import com.nisemoe.nise.database.UserService
import com.nisemoe.nise.service.AuthService
import com.nisemoe.nise.service.UpdateUserQueueService
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*

@RestController
class UserDetailsController(
    private val scoreService: ScoreService,
    private val authService: AuthService,
    private val userService: UserService,
    private val userQueueService: UpdateUserQueueService
) {

    data class UserDetailsResponse(
        val user_details: UserDetails,
        val queue_details: UserQueueDetails,
        val suspicious_scores: List<SuspiciousScoreEntry>,
        val similar_replays: List<SimilarReplayEntry>,
        val total_scores: Int = 0,
    )

    data class UserQueueRequest(
        val userId: Long
    )

    @PostMapping("user-queue")
    fun addUserToQueue(@RequestBody request: UserQueueRequest): ResponseEntity<Unit> {
        // Check if the user_id currently exists
        this.userService.getUserById(userId = request.userId)
            ?: return ResponseEntity.notFound().build()

        val userQueueDetails = this.userQueueService.getUserQueueDetails(request.userId)
        if(!userQueueDetails.canUpdate)
            return ResponseEntity.badRequest().build()

        val inserted = this.userQueueService.insertUser(request.userId, addedByUserId = this.authService.getCurrentUser().userId)

        return if(inserted)
            ResponseEntity.ok().build()
        else
            ResponseEntity.badRequest().build()
    }

    data class UserDetailsRequest(
        val userId: String
    )

    @PostMapping("user-details")
    fun getUserDetails(@RequestBody request: UserDetailsRequest): ResponseEntity<UserDetailsResponse> {
        val userDetails = this.userService.getUserDetails(username = request.userId)
            ?: return ResponseEntity.notFound().build()

        var suspiciousScoresCondition = this.scoreService.getDefaultCondition()
        suspiciousScoresCondition = suspiciousScoresCondition.and(SCORES.USER_ID.eq(userDetails.user_id))

        val response = UserDetailsResponse(
            user_details = userDetails,
            queue_details = this.userQueueService.getUserQueueDetails(userDetails.user_id),
            suspicious_scores = this.scoreService.getSuspiciousScores(suspiciousScoresCondition),
            similar_replays = this.scoreService.getSimilarReplaysForUserId(userDetails.user_id),
            total_scores = this.userService.getTotalUserScores(userDetails.user_id)
        )
        return ResponseEntity.ok(response)
    }

}