package com.test.bijihoudaun.controller;

import com.test.bijihoudaun.common.response.R;
import com.test.bijihoudaun.service.RegistrationCodeService;
import com.test.bijihoudaun.service.SystemSettingService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/system")
@Tag(name = "系统管理")
public class SystemController {

    @Autowired
    private SystemSettingService systemSettingService;

    @Autowired
    private RegistrationCodeService registrationCodeService;

    @GetMapping("/registration/status")
    @Operation(summary = "获取注册功能状态")
    public R<Boolean> isRegistrationEnabled() {
        return R.success(systemSettingService.isRegistrationEnabled());
    }

    @PostMapping("/registration/toggle")
    @PreAuthorize("hasRole('ADMIN')")
    @Operation(summary = "切换注册功能状态")
    public R<Void> toggleRegistration(@RequestBody Boolean enabled) {
        systemSettingService.setRegistrationEnabled(enabled);
        return R.success();
    }

    @PostMapping("/registration/generate-code")
    @PreAuthorize("hasRole('ADMIN')")
    @Operation(summary = "生成注册码")
    public R<String> generateRegistrationCode() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        String code = registrationCodeService.generateCode(currentUserName);
        return R.success(code);
    }
}
