package com.betriebsratkanzlei.legalconsenthub.application_form_version

import com.betriebsratkanzlei.legalconsenthub.application_form.ApplicationFormMapper
import com.betriebsratkanzlei.legalconsenthub.user.UserService
import com.betriebsratkanzlei.legalconsenthub_api.api.ApplicationFormVersionApi
import com.betriebsratkanzlei.legalconsenthub_api.model.ApplicationFormDto
import com.betriebsratkanzlei.legalconsenthub_api.model.ApplicationFormVersionDto
import com.betriebsratkanzlei.legalconsenthub_api.model.ApplicationFormVersionListItemDto
import org.springframework.http.ResponseEntity
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.web.bind.annotation.RestController
import java.util.UUID

@RestController
class ApplicationFormVersionController(
    private val versionService: ApplicationFormVersionService,
    private val versionMapper: ApplicationFormVersionMapper,
    private val applicationFormMapper: ApplicationFormMapper,
    private val userService: UserService,
) : ApplicationFormVersionApi {
    @PreAuthorize(
        "hasAnyRole('CHIEF_EXECUTIVE_OFFICER', 'BUSINESS_DEPARTMENT', 'IT_DEPARTMENT', 'HUMAN_RESOURCES', 'HEAD_OF_WORKS_COUNCIL', 'WORKS_COUNCIL', 'EMPLOYEE')",
    )
    override fun getApplicationFormVersions(id: UUID): ResponseEntity<List<ApplicationFormVersionListItemDto>> {
        val versions = versionService.getVersionsByApplicationFormId(id)
        return ResponseEntity.ok(versions.map { versionMapper.toApplicationFormVersionListItemDto(it) })
    }

    @PreAuthorize(
        "hasAnyRole('CHIEF_EXECUTIVE_OFFICER', 'BUSINESS_DEPARTMENT', 'IT_DEPARTMENT', 'HUMAN_RESOURCES', 'HEAD_OF_WORKS_COUNCIL', 'WORKS_COUNCIL', 'EMPLOYEE')",
    )
    override fun getApplicationFormVersion(
        id: UUID,
        versionNumber: Int,
    ): ResponseEntity<ApplicationFormVersionDto> {
        val version = versionService.getVersion(id, versionNumber)
        return ResponseEntity.ok(versionMapper.toApplicationFormVersionDto(version))
    }

    @PreAuthorize(
        "hasAnyRole('CHIEF_EXECUTIVE_OFFICER', 'BUSINESS_DEPARTMENT', 'IT_DEPARTMENT', 'HUMAN_RESOURCES', 'HEAD_OF_WORKS_COUNCIL', 'WORKS_COUNCIL')",
    )
    override fun restoreApplicationFormVersion(
        id: UUID,
        versionNumber: Int,
    ): ResponseEntity<ApplicationFormDto> {
        val currentUser = userService.getCurrentUser()
        val restoredForm = versionService.restoreVersion(id, versionNumber, currentUser)
        return ResponseEntity.ok(applicationFormMapper.toApplicationFormDto(restoredForm))
    }
}
