package com.mvrent.carrental.service;

import jakarta.annotation.PostConstruct;
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;

/**
 * Stores uploaded files (documents, photos) under a configurable local directory
 * and returns a public URL path (served by the resource handler in {@code WebConfig}).
 */
@Service
public class FileStorageService {

    private final Path root;
    private final String urlPrefix;

    public FileStorageService(@Value("${app.storage.location}") String location,
                              @Value("${app.storage.url-prefix}") String urlPrefix) {
        this.root = Paths.get(location).toAbsolutePath().normalize();
        this.urlPrefix = urlPrefix.endsWith("/") ? urlPrefix.substring(0, urlPrefix.length() - 1) : urlPrefix;
    }

    @PostConstruct
    void init() {
        try {
            Files.createDirectories(root);
        } catch (IOException e) {
            throw new IllegalStateException("Cannot create storage dir: " + root, e);
        }
    }

    /** Stores the file and returns its public URL path, or null if no file was uploaded. */
    public String store(MultipartFile file) {
        if (file == null || file.isEmpty()) return null;
        String original = file.getOriginalFilename() == null ? "" : file.getOriginalFilename();
        String ext = "";
        int dot = original.lastIndexOf('.');
        if (dot >= 0 && dot < original.length() - 1) {
            ext = original.substring(dot).replaceAll("[^A-Za-z0-9.]", "");
        }
        String name = UUID.randomUUID() + ext;
        try {
            Path target = root.resolve(name).normalize();
            if (!target.startsWith(root)) {
                throw new IllegalArgumentException("Invalid file path");
            }
            Files.copy(file.getInputStream(), target, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new RuntimeException("Failed to store file: " + e.getMessage(), e);
        }
        return urlPrefix + "/" + name;
    }
}
