package com.reading.platform.controller.admin;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reading.platform.common.annotation.RequireRole;
import com.reading.platform.common.enums.UserRole;
import com.reading.platform.common.response.PageResult;
import com.reading.platform.common.response.Result;
import com.reading.platform.dto.request.TenantCreateRequest;
import com.reading.platform.dto.request.TenantUpdateRequest;
import com.reading.platform.dto.request.TenantStatusUpdateRequest;
import com.reading.platform.dto.request.TenantQuotaUpdateRequest;
import com.reading.platform.dto.response.TenantResponse;
import com.reading.platform.dto.response.TenantStatusUpdateResponse;
import com.reading.platform.dto.response.ResetPasswordResponse;
import com.reading.platform.entity.Tenant;
import com.reading.platform.service.TenantService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

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

@Tag(name = "管理员 - 租户", description = "租户管理接口（管理员专用）")
@RestController
@RequestMapping("/api/v1/admin/tenants")
@RequiredArgsConstructor
@RequireRole(UserRole.ADMIN)
public class AdminTenantController {

    private final TenantService tenantService;

    @Operation(summary = "创建租户")
    @PostMapping
    public Result<Tenant> createTenant(@Valid @RequestBody TenantCreateRequest request) {
        return Result.success(tenantService.createTenant(request));
    }

    @Operation(summary = "更新租户")
    @PutMapping("/{id}")
    public Result<Tenant> updateTenant(@PathVariable String id, @RequestBody TenantUpdateRequest request) {
        return Result.success(tenantService.updateTenant(id, request));
    }

    @Operation(summary = "根据ID获取租户")
    @GetMapping("/{id}")
    public Result<Tenant> getTenant(@PathVariable String id) {
        return Result.success(tenantService.getTenantById(id));
    }

    @Operation(summary = "获取租户分页")
    @GetMapping
    public Result<PageResult<Tenant>> getTenantPage(
            @RequestParam(value = "page", required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String packageType) {
        Page<Tenant> page = tenantService.getTenantPage(pageNum, pageSize, keyword, status);
        return Result.success(PageResult.of(page));
    }

    @Operation(summary = "删除租户")
    @DeleteMapping("/{id}")
    public Result<Void> deleteTenant(@PathVariable String id) {
        tenantService.deleteTenant(id);
        return Result.success();
    }

    @Operation(summary = "获取所有活跃租户")
    @GetMapping("/active")
    public Result<List<TenantResponse>> getAllActiveTenants() {
        return Result.success(tenantService.getAllActiveTenants());
    }

    @Operation(summary = "更新租户状态")
    @PutMapping("/{id}/status")
    public Result<TenantStatusUpdateResponse> updateTenantStatus(
            @PathVariable String id,
            @RequestBody TenantStatusUpdateRequest request) {
        // Normalize status to lowercase for DB
        String dbStatus = request.getStatus() != null ? request.getStatus().toLowerCase() : "active";
        TenantUpdateRequest req = new TenantUpdateRequest();
        req.setStatus(dbStatus);
        Tenant tenant = tenantService.updateTenant(id, req);

        TenantStatusUpdateResponse response = new TenantStatusUpdateResponse();
        response.setId(tenant.getId());
        response.setName(tenant.getName());
        response.setStatus(tenant.getStatus());
        return Result.success(response);
    }

    @Operation(summary = "重置租户学校账号密码")
    @PostMapping("/{id}/reset-password")
    public Result<ResetPasswordResponse> resetTenantPassword(@PathVariable String id) {
        String tempPassword = tenantService.resetSchoolAccountPassword(id);
        ResetPasswordResponse response = ResetPasswordResponse.of(tempPassword, "请通知用户及时修改密码");
        return Result.success(response);
    }

    @Operation(summary = "更新租户配额")
    @PutMapping("/{id}/quota")
    public Result<Tenant> updateTenantQuota(
            @PathVariable String id,
            @RequestBody TenantQuotaUpdateRequest request) {
        TenantUpdateRequest req = new TenantUpdateRequest();
        if (request.getTeacherQuota() != null) {
            req.setMaxTeachers(request.getTeacherQuota());
        }
        if (request.getStudentQuota() != null) {
            req.setMaxStudents(request.getStudentQuota());
        }
        if (request.getPackageType() != null) {
            req.setPackageType(request.getPackageType());
        }
        return Result.success(tenantService.updateTenant(id, req));
    }

}
