package com.erp.ai.controller;

import com.erp.ai.dto.ApiKeyCreateRequest;
import com.erp.ai.service.AiAgentApiKeyService;
import com.erp.dto.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/ai-agents/keys")
@RequiredArgsConstructor
@Slf4j
public class AiAgentApiKeyController {

    private final AiAgentApiKeyService apiKeyService;

    @GetMapping(value = {"", "/list"})
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> list(
            @RequestAttribute(value = "user_id", required = false) String userId,
            @RequestAttribute(value = "role", required = false) String role) {
        boolean isAdmin = "SUPER_ADMIN".equals(role) || "COMPANY_ADMIN".equals(role);
        return ResponseEntity.ok(ApiResponse.success(
                apiKeyService.list(userId != null ? userId : "system", isAdmin)));
    }

    @PostMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> create(
            @RequestAttribute(value = "user_id", required = false) String userId,
            @RequestAttribute(value = "company_code", required = false) String companyCode,
            @RequestBody ApiKeyCreateRequest req) {
        AiAgentApiKeyService.CreatedKey result = apiKeyService.create(req,
                userId != null ? userId : "system", companyCode);
        Map<String, Object> data = new HashMap<>();
        data.put("id", result.key().getId());
        data.put("name", result.key().getName());
        data.put("key_prefix", result.key().getKey_prefix());
        data.put("user_id", result.key().getUser_id());
        data.put("agent_id", result.key().getAgent_id());
        data.put("permissions", result.key().getPermissions());
        data.put("rate_limit", result.key().getRate_limit());
        data.put("monthly_token_limit", result.key().getMonthly_token_limit());
        data.put("status", result.key().getStatus());
        data.put("expires_at", result.key().getExpires_at());
        data.put("created_at", result.key().getCreated_at());
        data.put("plain_key", result.plainKey());
        return ResponseEntity.status(201).body(
                ApiResponse.success(data, "API 키가 생성되었습니다. 키는 한 번만 표시됩니다."));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> revoke(
            @PathVariable long id,
            @RequestAttribute(value = "user_id", required = false) String userId) {
        apiKeyService.revoke(id, userId != null ? userId : "system");
        return ResponseEntity.ok(ApiResponse.success(null, "API 키가 폐기되었습니다."));
    }
}
