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.security.SecurityUtils;
import com.reading.platform.service.ExportService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.LocalDate;

@Tag(name = "学校 - 导出", description = "学校数据导出接口（学校管理员专用）")
@RestController
@RequestMapping("/api/v1/school/export")
@RequiredArgsConstructor
@RequireRole(UserRole.SCHOOL)
public class SchoolExportController {

    private final ExportService exportService;

    @Operation(summary = "导出教师信息到Excel")
    @GetMapping("/teachers")
    public ResponseEntity<byte[]> exportTeachers() throws IOException {
        String tenantId = SecurityUtils.getCurrentTenantId();
        byte[] data = exportService.exportTeachers(tenantId);
        return buildResponse(data, "teachers_" + LocalDate.now() + ".xlsx");
    }

    @Operation(summary = "导出学生信息到Excel")
    @GetMapping("/students")
    public ResponseEntity<byte[]> exportStudents() throws IOException {
        String tenantId = SecurityUtils.getCurrentTenantId();
        byte[] data = exportService.exportStudents(tenantId);
        return buildResponse(data, "students_" + LocalDate.now() + ".xlsx");
    }

    @Operation(summary = "导出课时信息到Excel")
    @GetMapping("/lessons")
    public ResponseEntity<byte[]> exportLessons() throws IOException {
        String tenantId = SecurityUtils.getCurrentTenantId();
        byte[] data = exportService.exportLessons(tenantId);
        return buildResponse(data, "lessons_" + LocalDate.now() + ".xlsx");
    }

    @Operation(summary = "导出成长档案到Excel")
    @GetMapping("/growth-records")
    public ResponseEntity<byte[]> exportGrowthRecords() throws IOException {
        String tenantId = SecurityUtils.getCurrentTenantId();
        byte[] data = exportService.exportGrowthRecords(tenantId);
        return buildResponse(data, "growth_records_" + LocalDate.now() + ".xlsx");
    }

    private ResponseEntity<byte[]> buildResponse(byte[] data, String filename) {
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
                .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                .body(data);
    }
}
