package kr.itn.itnhub.shared;

import kr.itn.itnhub.org.OrgNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/** 자료실(요구사항 [26]: 공용 양식 보관소)이 쓰는 서비스. */
@Service
public class SharedFileService {

    private final SharedFileMapper mapper;

    public SharedFileService(SharedFileMapper mapper) {
        this.mapper = mapper;
    }

    public List<SharedFile> list() {
        return mapper.findAll();
    }

    @Transactional
    public List<SharedFile> add(String fileName, String description, String contentType,
                                byte[] content, String uploadedBy) {
        if (content == null || content.length == 0) {
            throw new IllegalArgumentException("빈 파일은 올릴 수 없습니다.");
        }
        mapper.insert(fileName, blankToNull(description), contentType, content.length,
                content, uploadedBy);
        return mapper.findAll();
    }

    @Transactional
    public List<SharedFile> updateDescription(Long id, String description) {
        if (mapper.updateDescription(id, blankToNull(description)) == 0) {
            throw new OrgNotFoundException("자료를 찾을 수 없습니다: " + id);
        }
        return mapper.findAll();
    }

    public SharedFileMapper.Content content(Long id) {
        SharedFileMapper.Content found = mapper.findContent(id);
        if (found == null) {
            throw new OrgNotFoundException("자료를 찾을 수 없습니다: " + id);
        }
        return found;
    }

    @Transactional
    public void delete(Long id) {
        if (mapper.delete(id) == 0) {
            throw new OrgNotFoundException("자료를 찾을 수 없습니다: " + id);
        }
    }

    private String blankToNull(String value) {
        return (value == null || value.isBlank()) ? null : value.trim();
    }
}
