package com.writeoff.module.auth.controller;

import com.writeoff.common.api.ApiResponse;
import com.writeoff.module.auth.dto.PlatformSessionRevokePrincipalRequest;
import com.writeoff.module.auth.model.PlatformAuthSessionInfo;
import com.writeoff.module.auth.service.PlatformAuthSessionService;
import com.writeoff.security.DataScopeType;
import com.writeoff.security.PermissionDomain;
import com.writeoff.security.RequirePermission;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/platform/auth-sessions")
public class PlatformAuthSessionController {
    private final PlatformAuthSessionService platformAuthSessionService;

    public PlatformAuthSessionController(PlatformAuthSessionService platformAuthSessionService) {
        this.platformAuthSessionService = platformAuthSessionService;
    }

    @GetMapping
    @RequirePermission(value = "platform.session.read", domain = PermissionDomain.PLATFORM, dataScope = DataScopeType.GLOBAL_READONLY, auditAction = "PLATFORM_AUTH_SESSION_LIST")
    public ApiResponse<List<PlatformAuthSessionInfo>> list(
            @RequestParam(value = "scope", required = false) String scope,
            @RequestParam(value = "status", required = false) String status,
            @RequestParam(value = "userId", required = false) Long userId,
            @RequestParam(value = "tenantId", required = false) Long tenantId
    ) {
        return ApiResponse.success(platformAuthSessionService.list(scope, status, userId, tenantId));
    }

    @PostMapping("/{id}/revoke")
    @RequirePermission(value = "platform.session.manage", domain = PermissionDomain.PLATFORM, dataScope = DataScopeType.GLOBAL_READONLY, auditAction = "PLATFORM_AUTH_SESSION_REVOKE")
    public ApiResponse<Map<String, Object>> revoke(@PathVariable("id") Long id) {
        return ApiResponse.success(platformAuthSessionService.revokeBySessionId(id));
    }

    @PostMapping("/revoke-principal")
    @RequirePermission(value = "platform.session.manage", domain = PermissionDomain.PLATFORM, dataScope = DataScopeType.GLOBAL_READONLY, auditAction = "PLATFORM_AUTH_SESSION_REVOKE_PRINCIPAL")
    public ApiResponse<Map<String, Object>> revokePrincipal(@RequestBody @Valid PlatformSessionRevokePrincipalRequest request) {
        return ApiResponse.success(
                platformAuthSessionService.revokeByPrincipal(
                        request.getUserId(),
                        request.getTenantId(),
                        request.getScope()
                )
        );
    }
}
