package com.lesingle.edu.controller.school;

import com.lesingle.edu.common.annotation.Log;
import com.lesingle.edu.common.enums.LogModule;
import com.lesingle.edu.common.enums.LogOperationType;
import com.lesingle.edu.common.annotation.RequireRole;
import com.lesingle.edu.common.enums.UserRole;
import com.lesingle.edu.common.response.Result;
import com.lesingle.edu.common.security.SecurityUtils;
import com.lesingle.edu.dto.request.RenewRequest;
import com.lesingle.edu.dto.response.CourseCollectionResponse;
import com.lesingle.edu.dto.response.CourseResponse;
import com.lesingle.edu.dto.response.CoursePackageResponse;
import com.lesingle.edu.dto.response.PackageFilterMetaResponse;
import com.lesingle.edu.dto.response.PackageInfoResponse;
import com.lesingle.edu.dto.response.PackageUsageResponse;
import com.lesingle.edu.entity.Tenant;
import com.lesingle.edu.service.CourseCollectionService;
import com.lesingle.edu.service.CoursePackageService;
import com.lesingle.edu.service.TenantService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 课程套餐控制器（学校端）
 */
@RestController
@RequestMapping("/api/v1/school/packages")
@RequiredArgsConstructor
@Tag(name = "学校端 - 课程套餐")
public class SchoolPackageController {

    private final CourseCollectionService collectionService;
    private final CoursePackageService packageService;
    private final TenantService tenantService;

    @GetMapping
    @Operation(summary = "查询租户课程套餐（两层结构-最上层）")
    @RequireRole({UserRole.SCHOOL, UserRole.TEACHER})
    public Result<List<CourseCollectionResponse>> findTenantCollections() {
        Long tenantId = SecurityUtils.getCurrentTenantId();
        return Result.success(collectionService.findTenantCollections(tenantId));
    }

    @GetMapping("/{collectionId}/packages")
    @Operation(summary = "获取课程套餐下的课程包列表")
    @RequireRole({UserRole.SCHOOL, UserRole.TEACHER})
    public Result<List<CoursePackageResponse>> getPackagesByCollection(
            @PathVariable Long collectionId,
            @RequestParam(required = false) String grade,
            @RequestParam(required = false) String lessonType,
            @RequestParam(required = false) Long themeId,
            @RequestParam(required = false) String keyword) {
        return Result.success(collectionService.getPackagesByCollection(collectionId, grade, lessonType, themeId, keyword));
    }

    @GetMapping("/{collectionId}/filter-meta")
    @Operation(summary = "获取套餐筛选元数据（年级、课程配置选项）")
    @RequireRole({UserRole.SCHOOL, UserRole.TEACHER})
    public Result<PackageFilterMetaResponse> getFilterMeta(@PathVariable Long collectionId) {
        return Result.success(collectionService.getPackageFilterMeta(collectionId));
    }

    @PostMapping("/{collectionId}/renew")
    @Operation(summary = "续费课程套餐")
    @Log(module = LogModule.PACKAGE, type = LogOperationType.UPDATE, description = "续费课程套餐")
    @RequireRole(UserRole.SCHOOL)
    public Result<Void> renewCollection(
            @PathVariable Long collectionId,
            @RequestBody RenewRequest request) {
        Long tenantId = SecurityUtils.getCurrentTenantId();
        collectionService.renewTenantCollection(tenantId, collectionId, request.getEndDate(), request.getPricePaid());
        return Result.success();
    }

    @GetMapping("/packages/{packageId}/courses")
    @Operation(summary = "获取课程包下的课程列表（包含排课计划参考）")
    @RequireRole(UserRole.SCHOOL)
    public Result<CourseResponse> getPackageCourses(@PathVariable Long packageId) {
        return Result.success(packageService.getCourseByIdWithLessons(packageId));
    }


    @GetMapping("/package")
    @Operation(summary = "获取套餐信息")
    @RequireRole(UserRole.SCHOOL)
    public Result<PackageInfoResponse> getPackageInfo() {
        Long tenantId = SecurityUtils.getCurrentTenantId();
        Tenant tenant = tenantService.getById(tenantId);
        if (tenant == null) {
            return Result.success(null);
        }

        return Result.success(PackageInfoResponse.builder()
                .name(tenant.getName())
                .code(tenant.getCode())
                .status(tenant.getStatus())
                .expireDate(tenant.getExpireAt())
                .maxTeachers(tenant.getMaxTeachers())
                .maxStudents(tenant.getMaxStudents())
                .build());
    }

    @GetMapping("/package/usage")
    @Operation(summary = "获取套餐使用情况")
    @RequireRole(UserRole.SCHOOL)
    public Result<PackageUsageResponse> getPackageUsage() {
        Long tenantId = SecurityUtils.getCurrentTenantId();
        Tenant tenant = tenantService.getById(tenantId);
        if (tenant == null) {
            return Result.success(null);
        }

        // TODO: 获取教师数量和学生数量
        int teacherCount = 0;
        int studentCount = 0;

        PackageUsageResponse.UsageInfo teacherInfo = PackageUsageResponse.UsageInfo.builder()
                .used(teacherCount)
                .quota(tenant.getMaxTeachers())
                .percentage(tenant.getMaxTeachers() != null && tenant.getMaxTeachers() > 0
                        ? Math.round((float) teacherCount / tenant.getMaxTeachers() * 100) : 0)
                .build();

        PackageUsageResponse.UsageInfo studentInfo = PackageUsageResponse.UsageInfo.builder()
                .used(studentCount)
                .quota(tenant.getMaxStudents())
                .percentage(tenant.getMaxStudents() != null && tenant.getMaxStudents() > 0
                        ? Math.round((float) studentCount / tenant.getMaxStudents() * 100) : 0)
                .build();

        return Result.success(PackageUsageResponse.builder()
                .teacher(teacherInfo)
                .student(studentInfo)
                .build());
    }
}
