package com.betriebsratkanzlei.legalconsenthub.user

import com.betriebsratkanzlei.legalconsenthub.security.CustomJwtTokenPrincipal
import com.betriebsratkanzlei.legalconsenthub_api.api.UserApi
import com.betriebsratkanzlei.legalconsenthub_api.model.CreateUserDto
import com.betriebsratkanzlei.legalconsenthub_api.model.UserDto
import org.springframework.http.ResponseEntity
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.web.bind.annotation.RestController

@RestController
class UserController(
    private val userService: UserService,
    private val userMapper: UserMapper
) : UserApi {

    override fun createUser(createUserDto: CreateUserDto): ResponseEntity<UserDto> {
        val user = userService.createUser(createUserDto)
        return ResponseEntity.status(201).body(userMapper.toUserDto(user))
    }

    override fun getUserById(id: String): ResponseEntity<UserDto> {
        val user = userService.getUserById(id)
        return ResponseEntity.ok(userMapper.toUserDto(user))
    }

    override fun updateUser(id: String, userDto: UserDto?): ResponseEntity<UserDto> {
        val user = if (userDto != null) {
            // Update with provided data
            userService.updateUser(id, userDto)
        } else {
            // Update from JWT data
            val principal = SecurityContextHolder.getContext().authentication.principal as CustomJwtTokenPrincipal
            val userId = principal.id ?: throw IllegalArgumentException("User ID missing from JWT")
            val organizationId = principal.organizationId
            val roles = principal.roles
            
            userService.updateUserFromJwt(userId, organizationId, roles)
        }
        return ResponseEntity.ok(userMapper.toUserDto(user))
    }

    override fun deleteUser(id: String): ResponseEntity<Unit> {
        userService.deleteUser(id)
        return ResponseEntity.noContent().build()
    }
}
