package com.gameplatform.server.controller.admin;

import com.gameplatform.server.model.dto.account.*;
import com.gameplatform.server.model.dto.common.PageResult;
import com.gameplatform.server.service.account.AccountService;
import com.gameplatform.server.security.JwtService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import javax.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping("/api/admin/accounts")
@Tag(name = "管理员账户管理", description = "管理员账户的增删改查操作")
public class AccountController {
    private final AccountService accountService;
    private final JwtService jwtService;

    public AccountController(AccountService accountService, JwtService jwtService) {
        this.accountService = accountService;
        this.jwtService = jwtService;
    }

    @GetMapping
    @Operation(summary = "获取账户列表", description = "分页获取账户列表，支持按用户类型、状态、关键词筛选")
    public Mono<PageResult<AccountResponse>> list(
            @Parameter(description = "用户类型：ADMIN 或 AGENT") @RequestParam(value = "userType", required = false) String userType,
            @Parameter(description = "账户状态：ENABLED 或 DISABLED") @RequestParam(value = "status", required = false) String status,
            @Parameter(description = "搜索关键词") @RequestParam(value = "keyword", required = false) String keyword,
            @Parameter(description = "页码，默认1") @RequestParam(value = "page", required = false) Integer page,
            @Parameter(description = "每页大小，默认20，最大200") @RequestParam(value = "size", required = false) Integer size
    ) {
        return accountService.list(userType, status, keyword, page, size);
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    @Operation(summary = "创建账户", description = "创建新的管理员或代理账户")
    public Mono<AccountResponse> create(@Valid @RequestBody AccountCreateRequest req) {
        return accountService.create(req);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取账户详情", description = "根据账户ID获取账户详细信息")
    public Mono<AccountResponse> detail(@Parameter(description = "账户ID") @PathVariable Long id) {
        return accountService.get(id);
    }

    @PatchMapping("/{id}")
    @Operation(summary = "更新账户", description = "更新账户信息")
    public Mono<AccountResponse> update(@Parameter(description = "账户ID") @PathVariable Long id, @Valid @RequestBody AccountUpdateRequest req) {
        return accountService.update(id, req);
    }

    @PostMapping("/{id}/enable")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    @Operation(summary = "启用账户", description = "启用指定账户")
    public Mono<Void> enable(@Parameter(description = "账户ID") @PathVariable Long id) {
        return accountService.setStatus(id, "ENABLED").then();
    }

    @PostMapping("/{id}/disable")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    @Operation(summary = "禁用账户", description = "禁用指定账户")
    public Mono<Void> disable(@Parameter(description = "账户ID") @PathVariable Long id) {
        return accountService.setStatus(id, "DISABLED").then();
    }

    @PostMapping("/{id}/reset-password")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    @Operation(summary = "重置密码", description = "重置指定账户的密码")
    public Mono<Void> resetPassword(@Parameter(description = "账户ID") @PathVariable Long id, @Valid @RequestBody ResetPasswordRequest req) {
        return accountService.resetPassword(id, req.getNewPassword(), Boolean.TRUE.equals(req.getForceLogout()));
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    @Operation(summary = "删除用户", description = "删除指定的用户账户，管理员不能删除自己或最后一个管理员")
    public Mono<Void> delete(
            @Parameter(description = "账户ID") @PathVariable Long id,
            @Parameter(hidden = true) @RequestHeader("Authorization") String authHeader) {
        return Mono.fromCallable(() -> {
                    if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                        throw new IllegalArgumentException("Authorization header is required");
                    }
                    
                    String token = authHeader.substring(7);
                    io.jsonwebtoken.Claims claims = jwtService.parse(token);
                    Long currentUserId = claims.get("userId", Long.class);
                    
                    if (currentUserId == null) {
                        throw new IllegalArgumentException("Invalid token: userId not found");
                    }
                    
                    return currentUserId;
                })
                .flatMap(currentUserId -> accountService.delete(id, currentUserId))
                .then();
    }

    @GetMapping("/me/points-balance")
    @Operation(summary = "获取当前用户积分余额", description = "根据token解析用户ID并获取当前用户的积分余额")
    public Mono<PointsBalanceResponse> getCurrentUserPointsBalance(
            @Parameter(hidden = true) @RequestHeader("Authorization") String authHeader) {
        return Mono.fromCallable(() -> {
                    if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                        throw new IllegalArgumentException("Authorization header is required");
                    }
                    
                    String token = authHeader.substring(7);
                    io.jsonwebtoken.Claims claims = jwtService.parse(token);
                    Long userId = claims.get("userId", Long.class);
                    
                    if (userId == null) {
                        throw new IllegalArgumentException("Invalid token: userId not found");
                    }
                    
                    return userId;
                })
                .flatMap(accountService::getCurrentUserPointsBalance);
    }
}

