package com.reading.platform.controller.school;

import com.reading.platform.common.annotation.RequireRole;
import com.reading.platform.common.enums.UserRole;
import com.reading.platform.common.response.Result;
import com.reading.platform.common.security.SecurityUtils;
import com.reading.platform.dto.request.SchoolSettingsUpdateRequest;
import com.reading.platform.dto.response.SystemSettingsResponse;
import com.reading.platform.service.SystemSettingService;
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.Map;

@Tag(name = "学校 - 设置", description = "学校设置管理接口（学校管理员专用）")
@RestController
@RequestMapping("/api/v1/school/settings")
@RequiredArgsConstructor
@RequireRole(UserRole.SCHOOL)
public class SchoolSettingsController {

    private final SystemSettingService systemSettingService;

    @Operation(summary = "Get school settings")
    @GetMapping
    public Result<SystemSettingsResponse> getSettings() {
        String tenantId = SecurityUtils.getCurrentTenantId();
        Map<String, String> settings = systemSettingService.getSettings(tenantId);

        SystemSettingsResponse response = new SystemSettingsResponse();
        response.setSystemName(settings.get("systemName"));
        response.setSystemLogo(settings.get("systemLogo"));
        response.setLoginBackground(settings.get("loginBackground"));
        response.setAnnouncement(settings.get("announcement"));
        response.setContactInfo(settings.get("contactInfo"));

        return Result.success(response);
    }

    @Operation(summary = "Update school settings")
    @PutMapping
    public Result<Void> updateSettings(@RequestBody SchoolSettingsUpdateRequest request) {
        String tenantId = SecurityUtils.getCurrentTenantId();
        Map<String, String> settings = new java.util.HashMap<>();

        if (request.getSchoolName() != null) settings.put("schoolName", request.getSchoolName());
        if (request.getSchoolLogo() != null) settings.put("schoolLogo", request.getSchoolLogo());
        if (request.getAddress() != null) settings.put("address", request.getAddress());
        if (request.getNotifyOnLesson() != null) settings.put("notifyOnLesson", request.getNotifyOnLesson().toString());
        if (request.getNotifyOnTask() != null) settings.put("notifyOnTask", request.getNotifyOnTask().toString());
        if (request.getNotifyOnGrowth() != null) settings.put("notifyOnGrowth", request.getNotifyOnGrowth().toString());

        systemSettingService.updateSettings(tenantId, settings);
        return Result.success();
    }
}
