using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace SkyArtShop.Controllers;

[Route("api/upload")]
[Authorize(Roles = "Admin")]
public class ApiUploadController : Controller
{
	private readonly IWebHostEnvironment _environment;

	public ApiUploadController(IWebHostEnvironment environment)
	{
		_environment = environment;
	}

	[HttpPost("image")]
	public async Task<IActionResult> UploadImage(IFormFile image)
	{
		if (image == null || image.Length == 0L)
		{
			return Json(new
			{
				success = false,
				message = "No file uploaded"
			});
		}
		string[] source = new string[5] { ".jpg", ".jpeg", ".png", ".gif", ".webp" };
		string value = Path.GetExtension(image.FileName).ToLowerInvariant();
		if (!source.Contains(value))
		{
			return Json(new
			{
				success = false,
				message = "Invalid file type. Only images are allowed."
			});
		}
		try
		{
			string text = Path.Combine(_environment.WebRootPath, "uploads", "images");
			if (!Directory.Exists(text))
			{
				Directory.CreateDirectory(text);
			}
			string fileName = $"{Guid.NewGuid()}{value}";
			string path = Path.Combine(text, fileName);
			using (FileStream stream = new FileStream(path, FileMode.Create))
			{
				await image.CopyToAsync(stream);
			}
			string text2 = "/uploads/images/" + fileName;
			Console.WriteLine("[API-UPLOAD] Image uploaded successfully: " + text2);
			return Json(new
			{
				success = true,
				imageUrl = text2
			});
		}
		catch (Exception ex)
		{
			Console.WriteLine("[API-UPLOAD] Upload failed: " + ex.Message);
			return Json(new
			{
				success = false,
				message = "Upload failed: " + ex.Message
			});
		}
	}
}
