package com.owrawww.service;

import com.owrawww.domain.Careers;
import com.owrawww.domain.mapper.CareersMapper;
import com.owrawww.util.AesUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class CareersService {

    @Value("${app.upload.path}")
    private String uploadPath;

    private final CareersMapper careersMapper;
    private final AesUtil aesUtil;

    public boolean submit(Careers careers, MultipartFile file) throws IOException {
        Careers saved = new Careers();
        saved.setCode("1");
        saved.setTitle(careers.getTitle());
        saved.setComment(careers.getContent());
        saved.setName(careers.getName());
        saved.setTel(aesUtil.encrypt(careers.getTel()));
        saved.setTelHash(aesUtil.hash(careers.getTel()));
        saved.setEmail(aesUtil.encrypt(careers.getEmail()));
        saved.setEmailHash(aesUtil.hash(careers.getEmail()));
        saved.setTopCode(2);
        saved.setLeftCode(1);
        saved.setSubGubun(1);
        saved.setDepth(1);
        saved.setSolutionGubun(careers.getSolutionGubun());
        saved.setDept(careers.getDept());

        // 파일 저장
        if (file != null && !file.isEmpty()) {
            String originalName = file.getOriginalFilename() != null ? file.getOriginalFilename() : "unknown";
            String ext = originalName.contains(".")
                    ? originalName.substring(originalName.lastIndexOf('.'))
                    : "";
            String storedName = UUID.randomUUID().toString().replace("-", "") + ext;

            Path dir = Paths.get(uploadPath);
            Files.createDirectories(dir);
            Path dest = dir.resolve(storedName);
            Files.copy(file.getInputStream(), dest, StandardCopyOption.REPLACE_EXISTING);

            saved.setOrgFileName(originalName.replace(ext, "")); // 확장자 제외한 원본 파일명
            saved.setFileName(originalName);               // 원본 파일명
            saved.setFilePath(uploadPath + "/" + storedName); // 저장 경로      
            saved.setFileType(ext.isEmpty() ? "" : ext.substring(1)); // 확장자 (점 제외)
        }

        return careersMapper.insert(saved) > 0;
    }
}
