/*
 * 自然写教学资源管理与内容分发系统软件 V1.0
 * WritechResourceApplication.java - Spring Boot启动类与全局配置
 */
package com.writech.resource;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.TimeZone;
import java.util.logging.Logger;

/**
 * 自然写教学资源管理与内容分发系统启动类
 *
 * 功能概述：
 * - 课件/字帖/试卷模板管理
 * - 点阵码资源生成与管理
 * - 内容审核与版本控制
 * - 多终端资源分发与CDN缓存
 * - 教师自定义内容上传
 * - 按年级/学科/出版社分类检索
 * - 资源使用统计
 */
@SpringBootApplication
@EnableCaching
@EnableAsync
@EnableScheduling
@EnableConfigurationProperties
public class WritechResourceApplication {

    private static final Logger logger =
        Logger.getLogger(WritechResourceApplication.class.getName());

    public static void main(String[] args) {
        // 设置默认时区为东八区
        TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
        SpringApplication.run(WritechResourceApplication.class, args);
        logger.info("自然写资源管理平台已启动");
    }

    @PostConstruct
    public void init() {
        logger.info("资源平台初始化: 检查OSS连接、ES索引、CDN配置...");
        // 初始化OSS连接
        // 检查Elasticsearch索引是否存在，不存在则创建
        // 预热CDN缓存配置
    }

    @PreDestroy
    public void cleanup() {
        logger.info("资源平台关闭: 释放连接资源...");
    }

    /**
     * Web MVC配置：CORS跨域、拦截器
     */
    @Configuration
    static class WebConfig implements WebMvcConfigurer {

        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/api/**")
                .allowedOrigins(
                    "https://admin.writech.com",
                    "https://teacher.writech.com"
                )
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
        }

        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            // 审计日志拦截器：记录所有资源操作
            // registry.addInterceptor(new AuditLogInterceptor())
            //     .addPathPatterns("/api/**");

            // 权限校验拦截器：按学校/区域授权
            // registry.addInterceptor(new PermissionInterceptor())
            //     .addPathPatterns("/api/**")
            //     .excludePathPatterns("/api/v1/health");
        }
    }
}
