package app.mealsmadeeasy.api.file;

import app.mealsmadeeasy.api.s3.S3Manager;
import app.mealsmadeeasy.api.user.User;
import app.mealsmadeeasy.api.util.MimeTypeService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.time.OffsetDateTime;
import java.util.UUID;

@Service
public class FileService {

    private final FileRepository fileRepository;
    private final S3Manager s3Manager;
    private final MimeTypeService mimeTypeService;
    private final String filesBucket;

    public FileService(
            FileRepository fileRepository,
            S3Manager s3Manager,
            MimeTypeService mimeTypeService,
            @Value("${app.mealsmadeeasy.api.files.bucketName}") String filesBucket
    ) {
        this.fileRepository = fileRepository;
        this.s3Manager = s3Manager;
        this.mimeTypeService = mimeTypeService;
        this.filesBucket = filesBucket;
    }

    public File create(
            InputStream fileContent,
            String userFilename,
            long fileSize,
            User owner
    ) throws IOException {
        final UUID uuid = UUID.randomUUID();
        final String mimeType = this.mimeTypeService.getMimeType(userFilename);
        final String filename = uuid + "." + this.mimeTypeService.getExtension(mimeType);

        final String objectName = this.s3Manager.store(
                this.filesBucket,
                filename,
                mimeType,
                fileContent,
                fileSize
        );

        final var file = new File();
        file.setCreated(OffsetDateTime.now());
        file.setUserFilename(userFilename);
        file.setMimeType(mimeType);
        file.setObjectName(objectName);
        file.setOwner(owner);

        return this.fileRepository.save(file);
    }

    public InputStream getFileContentById(UUID fileId) throws IOException {
        final File file = this.fileRepository.findById(fileId).orElseThrow(() -> new IllegalArgumentException(
                "File with id " + fileId + " not found"
        ));
        return this.s3Manager.load(this.filesBucket, file.getObjectName());
    }

    public File getById(UUID id) {
        return this.fileRepository.findById(id).orElseThrow(() -> new IllegalArgumentException(
                "File with id " + id + " not found"
        ));
    }

}
