package com.nisemoe.nise.controller

import com.nisemoe.nise.integrations.MetabaseService
import com.nisemoe.nise.service.AuthService
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

@RestController
@RequestMapping("metabase")
class MetabaseController(
    private val authService: AuthService,
    private val metabaseService: MetabaseService
) {

    data class GetMetabaseUserResponse(
        val email: String
    )

    @GetMapping("status")
    fun getMetabaseStatus(): ResponseEntity<GetMetabaseUserResponse> {
        if(!this.authService.isLoggedIn() || !this.authService.isAdmin())
            return ResponseEntity.badRequest().build()

        val currentUser = this.authService.getCurrentUser()

        val metabaseUser = this.metabaseService.getUser(currentUser.username)
            ?: return ResponseEntity.notFound().build()

        return ResponseEntity.ok(GetMetabaseUserResponse(metabaseUser))
    }

    data class CreateMetabaseUserResponse(
        val email: String,
        val password: String
    )

    @GetMapping("create")
    fun createMetabaseUser(): ResponseEntity<CreateMetabaseUserResponse> {
        if(!this.authService.isLoggedIn() || !this.authService.isAdmin())
            return ResponseEntity.badRequest().build()

        val currentUser = this.authService.getCurrentUser()

        try {
            val newUser = this.metabaseService.createNewUser(currentUser.username)
            return ResponseEntity.ok(CreateMetabaseUserResponse(newUser.email, newUser.password))
        } catch (e: Exception) {
            return ResponseEntity.badRequest().build()
        }
    }

    @GetMapping("reset")
    fun resetMetabaseUser(): ResponseEntity<CreateMetabaseUserResponse> {
        if(!this.authService.isLoggedIn() || !this.authService.isAdmin())
            return ResponseEntity.badRequest().build()

        val currentUser = this.authService.getCurrentUser()

        try {
            val newUser = this.metabaseService.resetPassword(currentUser.username)
            return ResponseEntity.ok(CreateMetabaseUserResponse(newUser.email, newUser.password))
        } catch (e: Exception) {
            return ResponseEntity.badRequest().build()
        }
    }

}