package kr.itn.itnhub.contact;

import kr.itn.itnhub.seed.SeedParseException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/** 회원정보 xlsx 업로드. SeedController와 동일한 확장자/빈 파일 검증을 쓴다. */
@RestController
public class MemberImportController {

    private final MemberImportService importService;

    public MemberImportController(MemberImportService importService) {
        this.importService = importService;
    }

    @PostMapping("/api/contacts/import")
    public MemberImportReport upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            throw new SeedParseException("업로드된 파일이 비어 있습니다.");
        }
        String filename = file.getOriginalFilename();
        if (filename == null || !hasAllowedExtension(filename)) {
            throw new SeedParseException("엑셀 파일(.xlsx 또는 .xlsm)만 업로드할 수 있습니다.");
        }
        try (InputStream in = file.getInputStream()) {
            return importService.importFile(in);
        } catch (IOException e) {
            throw new SeedParseException("엑셀 파일을 읽지 못했습니다.", e);
        }
    }

    private static boolean hasAllowedExtension(String filename) {
        String lower = filename.toLowerCase();
        return lower.endsWith(".xlsx") || lower.endsWith(".xlsm");
    }
}
