package com.hertz.modules.system.controller;

import com.hertz.common.api.ApiResponse;
import com.hertz.common.exception.BusinessException;
import com.hertz.config.AppPathResolver;
import com.hertz.config.AppProperties;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/common/file")
@RequiredArgsConstructor
public class FileController {

  private final AppProperties appProperties;
  private final AppPathResolver pathResolver;

  @PostMapping("/upload")
  public ApiResponse<UploadResult> upload(@RequestParam("file") MultipartFile file) {
    if (file.isEmpty()) {
      throw new BusinessException(400, "File cannot be empty");
    }

    String originalFilename = file.getOriginalFilename();
    if (originalFilename == null) {
      throw new BusinessException(400, "Original filename is required");
    }
    String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
    if (!suffix.equalsIgnoreCase(".jpg") && !suffix.equalsIgnoreCase(".png") && !suffix.equalsIgnoreCase(".jpeg")) {
      throw new BusinessException(400, "Only JPG/PNG formats are supported");
    }

    if (file.getSize() > 2 * 1024 * 1024) {
      throw new BusinessException(400, "File size exceeds 2MB");
    }

    String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM"));
    String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
    String relativePath = appProperties.getUpload().getAvatarPath() + datePath + "/" + fileName;
    // Construct full path
    String fullPath = pathResolver.resolve(appProperties.getUpload().getRootPath()) + File.separator + relativePath;

    File dest = new File(fullPath);
    if (!dest.getParentFile().exists()) {
      dest.getParentFile().mkdirs();
    }

    try {
      file.transferTo(dest);

      // Return relative path. Frontend should prepend the base URL.
      return ApiResponse.ok(new UploadResult("/uploads/" + relativePath, null));
    } catch (IOException e) {
      throw new BusinessException(500, "File upload failed: " + e.getMessage());
    }
  }

  public record UploadResult(String url, String thumbUrl) {
  }
}
